Here's my gulp task to compile my ES6 code into a single ES5 file. I use classes and modules (import
, export
) in ES6.
gulp.src(paths.scripts)
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['es2015']
}))
.pipe(concat('all.js'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./www/js'));
However, because Babel compiles ES6 import
directives into require
commands, and require
will attempt to request a file, the request files are failing because all the ES5 code is concatted into one file, all.js.
The result is a bunch of "Error: Cannot find module" errors. How can I compile modules that work when they're all saved in a single file?
You're not the first one with the need of transpiling JSX/ES6 to ES5 with Babel but without using CommonJS modules and hence Browserify/Webpack. Unfortunately it turns out this is not possible at the time (1, 2, 3), and it looks like it won't be possible ever. You're pretty much forced to use these tools if you want to use ES6 transpiled with Babel, but you won't have the chance to use the resulting code with other concatenated/inline JavaScript (because of all those require()
calls rather than global variables on window
). It's a pity Babel doesn't allow to change this behaviour.
You will probably need Browserify to make it work with gulp:
browserify('./js/script.js', { debug: true })
.add(require.resolve('babel-polyfill'))
.transform(babelify.configure({presets: ['es2015']}))
.bundle()
.on('error', util.log.bind(util, 'Browserify Error'))
.pipe(source('all.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify({ mangle: false }))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./www/js'));
for example: https://github.com/glued/harp-babel/blob/babel-gulp-v6/gulpfile.babel.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With