Using Babel 6 + grunt to work with ES6 – how to transform require statements?

https://stackoverflow.com/questions/41067220/using-babel-grunt-to-work-with-es6-how-to-transform-require-statements

Browserify will handle the import bindings for the ES6 modules. Also a package named babelify will help to handle your babel browserify transform.

The following seems to work well:

Use babel-cli instead of babel.

Step 1. It’s worth noting that Babel has been replaced with babel-cli as of babel 6 (see their blog for more info on that).

So, firstly, remove/uninstall it from your package.json (if it exists!):

# Using `yarn` tool:
$ yarn remove --dev babel

# Or, `npm` tool:
$ npm uninstall babel --save-dev

… and uninstall grunt-babel:

# Using `yarn` tool:
$ yarn remove --dev grunt-babel

# Or, `npm` tool:
$ npm uninstall grunt-babel --save-dev

Step 2. Install babel-cli and also include the babel preset for all babel-preset-env plugins:

# Using `yarn` tool:
$ yarn add --dev babel-cli  babel-preset-env

# Or, `npm` tool:
$ npm install --save-dev babel-cli babel-preset-env

Step 3. Next, create a .babelrc file and save it in your projects root directory containing the following code:

    {
        "presets": ["env"]
    }

grunt-browserify package

Step 4. Next, install grunt-browserify and save it to your package.json:

# Using `yarn` tool:
$ yarn add --dev grunt-browserify

# Or, `npm` tool:
$ npm install grunt-browserify --save-dev

babelify package

Step 5. Install babelify to handle your babel browserify transform:

# Using `yarn` tool:
$ yarn add --dev  babelify

# Or, `npm` tool:
$ npm install babelify --save-dev

Gruntfile.js file

Step 6. Next update your Gruntfile.js by deleting the existing babel task:

    // DELETE the following...
    babel: {
        files: {
            expand: true,
            src: ['src/*.es6'],
            ext: '-compiled.js'
        },
        options: {
            sourceMap: true,
            presets: ['babel-preset-es2015']
        }
    },

Step 7. …and adding the following browserify task instead:

// Gruntfile.js:

    browserify: {
        dist: {
            files: {
                // destination for transpiled js : source js
                'dist/myproject.js': 'src/index.es6'
            },
            options: {
                transform: [['babelify', { presets: "env" }]],
                browserifyOptions: {
                    debug: true
                }
            }
        }
    }

Step 8. Registering your grunt tasks into Gruntfile.js : It’s likely that you will also need to update and change the order of the tasks in the array passed to grunt.registerTask.
To this:

// Gruntfile.js:

grunt.registerTask('default', [
    'jshint',
    //'concat', <-- Probably don't need to concat the files, assuming index.es6 imports the necessary modules.
    'browserify:dist',
    'uglify'
]);

Leave a Reply