BugHunterUK BugHunterUK - 6 months ago 136
Node.js Question

Gulp and Babel: Error: Cannot find module

I have a project that I've set up using

gulp
and
babel
. 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. 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
:

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:


  • app.js

  • hellojs



app.js

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


hello.js

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


And I run like so:

npm start


Which basically calls
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
. It wont find it though because its concatenated. Is that possible?

Answer

It is incorrect to concatenate two module files and expect the program to work properly, even when transpiled to 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. 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):

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/'));
});
Comments