简体   繁体   English

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

[英]Gulp and Babel: Error: Cannot find module

I have a project that I've set up using gulp and babel . 我有一个使用gulpbabel设置的项目。 Everything is working fine, except when I create a module and import it once it's converted from ES6 to ES6 it doesn't work. 一切工作正常,除非当我创建一个模块并将其从ES6转换为ES6并将其导入时,否则将无法正常工作。 I get an error: 我收到一个错误:

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)

Here's my gulpfile.babel.js : 这是我的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"]);

During build everything is concatenated into one file. 在构建过程中,所有内容都连接到一个文件中。 Under src/ I have: src/我有:

  • app.js app.js
  • hellojs hellojs

app.js app.js

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

hello.js hello.js

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

And I run like so: 我这样跑:

npm start

Which basically calls node ./build/build.js . 基本上调用node ./build/build.js

I think it's because it's concatenating the ES6 into ES5 and the bundle.js still contains the require for hello.js . 我认为这是因为它将ES6连接到ES5,并且bundle.js仍然包含hello.js It wont find it though because its concatenated. 它不会找到它,因为它是串联的。 Is that possible? 那可能吗?

It is incorrect to concatenate two module files and expect the program to work properly, even when transpiled to ES5. 串联两个模块文件并期望程序正常运行是不正确的,即使将其编译到ES5中也是如此。 Bundling involves more than concatenating the scripts: each module needs a closure for registering exports and resolving the contents of other modules. 捆绑不仅涉及串联脚本:每个模块都需要一个闭包来注册出口并解析其他模块的内容。

You must instead use a bundling tool such as Browserify, Webpack or Rollup. 相反,您必须使用捆绑工具,例如Br​​owserify,Webpack或Rollup。 Here's how one would bundle with Browserify (which in this case, it is easier to rely on the Babelify transform rather than gulp-babel ): 这是与Browserify捆绑在一起的方式(在这种情况下,依赖Babelify变换比gulp 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/'));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM