Gulp和Babel:错误:找不到模块

我有一个项目,我已经build立了使用大gulpbabel 。 一切工作正常,除了当我创build一个模块,并导入它从ES6转换到ES6它不起作用。 我收到一个错误:

 Error: Cannot find module 'hello.js' at Function.Module._resolveFilename (module.js:440:15) at Function.Module._load (module.js:388:25) at Module.require (module.js:468:17) 

这是我的gulpfile.babel.js

 import gulp from "gulp"; import babel from "gulp-babel" import concat from "gulp-concat" const dirs = { src: "src", dest: "build" } gulp.task("build", () => { return gulp.src(dirs.src + "/**/*.js") .pipe(babel()) .pipe(concat("build.js")) .pipe(gulp.dest(dirs.dest)) }); gulp.task("default", ["build"]); 

在构build过程中,所有内容都被连接成一个文件。 在src/我有:

  • app.js
  • hellojs

app.js

 import hello from './hello.js' console.log(hello()); 

hello.js

 export default () => { return 'Hey from hello.js'; }; 

我这样跑:

 npm start 

基本上调用node ./build/build.js

我认为这是因为它将ES6连接到ES5,而bundle.js仍然包含对hello.js 。 它不会find它,因为它连接在一起。 那可能吗?

连接两个模块文件并期望程序正常工作是不正确的,即使在转换成ES5时也是如此。 捆绑涉及的不仅仅是连接脚本:每个模块都需要一个闭包来注册导出并parsing其他模块的内容。

您必须改为使用捆绑工具,如Browserify,Webpack或Rollup。 以下是如何与Browserify进行捆绑(在这种情况下,依赖Babelify变换而不是一口气更容易):

 var browserify = require('browserify'); var gulp = require('gulp'); var source = require('vinyl-source-stream'); var babelify = require('babelify'); gulp.task('browserify', function() { return browserify({ entries: './src/app.js' }) .transform(babelify) .bundle() .pipe(source('bundle.js')) .pipe(gulp.dest('./build/')); });