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

时间:2016-06-01 23:22:43

标签: javascript node.js gulp ecmascript-6 babeljs

我有一个使用gulpbabel设置的项目。一切都运行正常,除非我创建一个模块并导入它,一旦它从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"]);

在构建期间,所有内容都连接成一个文件。在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的要求。它不会找到它,因为它连接在一起。这可能吗?

1 个答案:

答案 0 :(得分:2)

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

您必须使用诸如Browserify,Webpack或Rollup之类的捆绑工具。以下是如何捆绑Browserify(在这种情况下,更容易依赖Babelify转换而不是gulp-babel):

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/'));
});
相关问题