Gulp concat and require path

笑着哭i 提交于 2019-12-02 08:41:31

问题


I have a problem with gulp-concat. I'm trying to concate all my js files in a single file, let's say, dist/app.js.

But there is something that I don't understand. In that file, my required files path are still the same than before...

Here is my gulpfile.js :

var gulp       = require("gulp");
var sourcemaps = require("gulp-sourcemaps");
var babel      = require("gulp-babel");
var concat     = require("gulp-concat");
var resolveDependencies      = require("gulp-resolve-dependencies");

gulp.task("default", function () {
  return gulp.src("client/**/*.js")
    .pipe(sourcemaps.init())
    .pipe(babel())
    .pipe(concat("app.js"))
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest("dist/js"));
});

As you can see, I want to concat nested folders.

Take a look for example at the top of my /client/components/app.js :

import React, {PropTypes} from 'react';
import AppLeftNav from './AppLeftNav';
import {AppCanvas, AppBar, Styles} from 'material-ui';

//Code here

So in my app app.js generated by gulp, i can see :

var _AppLeftNav = require('./AppLeftNav');

It's a relative path and it can't work.

So, what's the tricks to handle theses required files with relative path ?

Thanks a lot.

EDIT : See the error I get :

Error: Cannot find module './components/App.js'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (MyFolder\dist\js\app.js:34:24)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)

回答1:


To anyone who might have the same problem. Babel currently doesn't support imports inlining #1681, neither do gulp-concat, as it's just concatenating files.

I opted to use Rollup to propertly resolve dependencies and only then transpile output:

var gulp = require('gulp');
var gutil = require('gulp-util');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var rollup = require('gulp-rollup');

gulp.task('build', function () {
  return gulp.src('src/parser-factory.js', { read: false })
    .pipe(rollup({ external: ['request', 'cheerio'] }))
    .on('error', gutil.log)
    .pipe(babel({ stage: 0 }))
    .pipe(concat('realty-parser.js'))
    .pipe(gulp.dest('lib'));
});



回答2:


If you want to get it all in a single file then you will have to write .pipe(gulp.dest("dist/js/jsfile.js")); where jsfile is the name of your file.



来源:https://stackoverflow.com/questions/31873235/gulp-concat-and-require-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!