Search code examples
javascriptgulpecmascript-6browserify

ES6 modules not working with babel 6 and gulp


I'm trying to understand how to use modules with babel 6 and gulp. I created some test files

file a.js

export function test () {
    console.log(11111);
}

file app.js

import {test} from 'a.js';
console.log(test());

file gulpfile.babel.js

import gulp from 'gulp';
import babel from 'gulp-babel';
import fs from 'fs';
import browserify from 'browserify'
import babelify from 'babelify';
import buffer from 'vinyl-buffer';
import source from 'vinyl-source-stream';
import uglify from 'gulp-uglify';


gulp.task('default', () => {
    var bundler = browserify('src/app.js');
    bundler.transform(babelify);

    bundler.bundle()
        .on('error', function (err) { console.error(err); })
        .pipe(source('app.js'))
        .pipe(buffer())
        .pipe(uglify()) 
        .pipe(gulp.dest('dist'));
});

package.json

{
  "name": "babel",
  "version": "1.0.0",
  "description": "",
  "main": "index.html",
  "dependencies": {
    "babel": "^6.5.2",
    "babel-preset-es2015": "^6.6.0",
    "babelify": "^7.2.0",
    "browserify": "^13.0.0",
    "fs": "^0.0.2",
    "gulp": "^3.9.1",
    "gulp-uglify": "^1.5.3",
    "gulp-babel": "^6.1.2",
    "vinyl-buffer": "^1.0.0",
    "vinyl-source-stream": "^1.1.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

.babelrc

{
  "presets": ["es2015"]
}

So, it's seems that all is correct, but when I run the gulp command, I see this error - [Error: Cannot find module 'a.js' from 'E:\JS\babel\src'] I cant understand why this error is happened and how to resolve it

Here in the repo on github - https://github.com/zheleznov/ecma-modules.git


Solution

  • If you refer to a file, you need to provide the path to the module file:

    ... from './a.js';
    

    Otherwise, Node will look for a module with name "a.js" in node_modules/.

    This has nothing to do with ES6 btw. That's how Node / browserify works. See the Node documentation.