Which tools do I need in order to use ES6 style imports for my project using Gulp?

408 views Asked by At

I have a legacy project which uses Gulp to compile SASS and minify JS etc. (based on Drupal).

I'd like to use ES6 style imports and also be able to import modules that are located in node_modules without referencing the full path (for example import the lodash.debounce module as

  import throttle from 'lodash.throttle'

What do I need to achieve that? (besides Gulp and NPM). Babel? Browserify? Lost with all the tooling.

I'd like to avoid webpack as it would increase the complexity of my project (and I don't know if I can use it in parallel with the way Drupal 7 is doing things)

2

There are 2 answers

6
AzMoo On BEST ANSWER

Yep, you want babel. The documentation to set it up in your gulpfile is here: http://babeljs.io/docs/setup/#installation

You'll want to use the es2015 preset to enable the import syntax.

var gulp = require("gulp");
var babel = require("gulp-babel");

gulp.task("default", function () {
  return gulp.src("src/app.js")
    .pipe(babel({
        presets: ['es2015']
     }))
    .pipe(gulp.dest("dist"));
});
3
Euan Smith On

To use import you need a transpiler, for example babel. Assuming you are building code for the browser then to use import (transpiled to require) you need webpack or browserify which will also allow you to import from node_modules (there are other module builders too, jspm and systemjs, however I know next-to-nothing about them). For either of these you will also need something to enable babel to be used in the build process. I use webpack with babel-loader.

I found a useful reference here specifically on using ES6 modules with webpack.