javascriptnode.jsgulpecmascript-6gulp-babel

Unexpected token { when trying gulp with JS ES6


Am I using wrong version of some package or can you post me a link to the detailed tutorial or codepen where this syntax construction do not give me an error?

I am getting this error:

$ gulp
D:\GIT\project02\gulpfile.js:20
const { COMPATIBILITY, PORT, UNCSS_OPTIONS, PATHS } = loadConfig();
      ^

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:413:25)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at execute (C:\Documents and Settings\Administrator\Application Data\npm\node_modules\gulp-cli\lib\versioned\^4.0.0-alpha.2\index.js:36:18)
    at Liftoff.handleArguments (C:\Documents and Settings\Administrator\Application Data\npm\node_modules\gulp-cli\index.js:172:63)
    at Liftoff.<anonymous> (C:\Documents and Settings\Administrator\Application Data\npm\node_modules\gulp-cli\node_modules\liftoff\index.js:198:16)

I've already read this question, but 'use strict'; was in my gulpfile, and changing const to let didn't worked for me.

My globally installed packages:

$ npm -g ls --depth=0
C:\Documents and Settings\Administrator\Application Data\npm
├── babel-cli@6.14.0
├── babel-core@6.14.0
├── babel-preset-es2015@6.14.0
├── bower@1.7.9
├── gulp-babel@6.1.2
└── gulp-cli@1.2.2 (git://github.com/gulpjs/gulp-cli.git#9b053ed9b7a63a10777c33b86b04ed38d7f5b840)

My Node is v4.0.0 and gulp that I am using in project:

$ gulp -v
[14:15:06] CLI version 1.2.2
[14:15:06] Local version 4.0.0-alpha.2

Solution

  • As Konstantin already said, not all ES6 features are available in your Gulpfile, because node has to process those files. But there is an easy way to do this by using the babel-require hook.

    Create a Gulpfile like this:

    'use strict';
    
    // Compile task to ES5 on the fly!
    require('babel-register');
    
    // Require all tasks!
    require('require-dir')('./tasks', { recurse: true });
    

    and put your tasks inside the tasks directory. Then create a .babelrc file to load a preset, e.g.

    {
        "presets": ["node5"]
    }
    

    when you're using node v5.x. Now you can use ES6 features! :)