0

I would like to use the features of ES2016 for my front end development. Especially import and decorators are interesting for me.

I’ve started a small test project and created some different files with classes which I include with import. Babel generates the correct files but includes an require statement which does not work in a browser (as far as I know).

Are there any good tools to concat all files into a single javascript file ordered by their require? Or some libraries for gulp which do this for me?

Pablo Christiano
  • 365
  • 3
  • 21

1 Answers1

3

You get the error because Babel translates your ES2016 code into CommonJS format, browser does not support it. You need some module bundler for creating bundle that can be used in browser:

  • Browserify
  • Webpack
  • Rollup

Example gulp build with gulp-rollup

// setup by `npm i gulp gulp-rollup rollup-plugin-babel babel-preset-es2016 babel-plugin-external-helpers --save-dev`

// gulpfile.js
var gulp       = require('gulp'),
    rollup     = require('gulp-rollup');

gulp.task('bundle', function() {
  gulp.src('./src/**/*.js')
    // transform the files here.
    .pipe(rollup({
      // any option supported by Rollup can be set here.
      "format": "iife",
      "plugins": [
        require("rollup-plugin-babel")({
          "presets": [["es2016", { "modules": false }]],
          "plugins": ["external-helpers"]
        })
      ],
      entry: './src/main.js'
    }))
    .pipe(gulp.dest('./dist'));
});
Maxim Kuzmin
  • 2,574
  • 19
  • 24
  • @pablo-christiano obviousely you should use https://www.npmjs.com/package/babel-preset-es2016 instead of babel-preset-es2015 – Maxim Kuzmin Jul 30 '17 at 10:19
  • Thanks for your help! this looks like exactly what i needed. I'm new to babel. Will there be any conflicts if i use the `stage-2` preset and the `transform-decorators-legacy` plugin within? – Pablo Christiano Jul 30 '17 at 10:27