Skip to content

Instantly share code, notes, and snippets.

@jodyheavener
Created August 18, 2015 04:55
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jodyheavener/27a7258b32a9ef80f2fd to your computer and use it in GitHub Desktop.
Save jodyheavener/27a7258b32a9ef80f2fd to your computer and use it in GitHub Desktop.
Use Babel (ES6) with Sails JS

Inspired by this issue, with these instructions you should be able to get Babel transpiling your JS in Sails JS for the client side.

  1. Install Grunt Babel npm install --save grunt-babel
  2. Create a babel.js file under tasks/config and add something like the following:
module.exports = function(grunt) {

    grunt.config.set('babel', {
      dev: {
        files: [{
          expand: true,
          cwd: 'assets/js/',
          src: ['**/*.js', '!dependencies/**/*.js'],
          dest: '.tmp/public/js/',
          ext: '.js'
        }]
      }
    });

    grunt.loadNpmTasks('grunt-babel');
};

It's up to you, but I'm not touching the dependencies folder.

  1. Since Babel copies the JS over, update the copy:dev tasks's src to exclude js (copy.js under tasks/config). It should looks something like this:
src: ['**/*.!(coffee|less|js)'],
  1. Update both compileAssets.js and syncAssets.js under tasks/config to include the Babel dev task: 'babel:dev'

That should do it. Try running sails lift --verbose to see if Babel is running, and then try writing some fancy ES6! If I'm missing something please advise.

@inakiarroyo
Copy link

Thanks a lot!
Only one thing, compileAssets.js and syncAssets.js are under task/register not under task/config

@derzunov
Copy link

derzunov commented Sep 3, 2016

In addition now you have to set up presets or it will just copy your js files without any changes

module.exports = function(grunt) {

    grunt.config.set('babel', {
        dev: {
            options: {
                presets: ['es2015', 'react']
            },
            files: [{
                expand: true,
                cwd: 'assets/js/',
                src: ['**/*.js', '!dependencies/**/*.js'],
                dest: '.tmp/public/js/',
                ext: '.js'
            }]
        }
    });

    grunt.loadNpmTasks('grunt-babel');
};

@niallobrien
Copy link

Thanks for sharing guys, much appreciated.

@ht512512
Copy link

ht512512 commented Sep 5, 2017

Thanks for the clear instructions.
es2015 preset does not handle Promise so the code like "foo = new Promise(...)" is passed through and of course IE 11 barfs on it. Any suggestion about how to get polyfill to work in the above setup? Thx.

@ht512512
Copy link

ht512512 commented Sep 5, 2017

Polyfill issue solved by using es6-promise-polyfill. Thx

@jmav
Copy link

jmav commented Oct 1, 2017

Don't forget to install babel-core
npm install babel-core babel-loader --save-dev

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment