How should I transform ES6 node_modules with browserify and babelify?

I’m using gulp, browserify and babelify in order to use ES6 syntax in my project. As soon as I import a node_module, which was also written in ES6, gulp throws an error: 'import' and 'export' may appear only with 'sourceType: module'

I’ve read the proposed solutions on babelify’s github page. In short, the two possibilities are:

  1. Add a browserify option to the affected node_module’s package.json
  2. Configure gulp, so that browserify tries to transform all files with babelify (and add an ignore-option for unnecessary files).

The first option would prevent others from being able to clone my project and get it up and running right away. Is there a workaround, perhaps using an npm postinstall script?

The second option seems like an overkill. Is there a more elegant solution for this?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Babelify has an only option that can be used to avoid transpiling files that don’t match a regular expression. When combined with Browserify’s global option (by default, transforms are not applied to files within the node_modules directory), you can selectively transpile files within node_modules.

With this example configuration:

browserify({ entries: ["index.js"] })
  .transform("babelify", {
    global: true,
    only: /^(?:.*\/node_modules\/(?:a|b)\/|(?!.*\/node_modules\/)).*$/,
    presets: ["es2015"]
  })
  .bundle()
  .pipe(fs.createWriteStream("bundle.js"));

files not within node_modules will not be compiled unless they are in one of:

  • /node_modules/a
  • /node_modules/b

If you have only one directory under node_modules that you want transpiled, you can simplify the regular expression to:

/^(?:.*\/node_modules\/a\/|(?!.*\/node_modules\/)).*$/

and if you have more, you can add them:

/^(?:.*\/node_modules\/(?:a|b|c|d)\/|(?!.*\/node_modules\/)).*$/

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply