Search code examples
node.jsbabeljsbabel-node

Object spread not working in Node 7.5


// Rest properties
require("babel-core").transform("code", {
  plugins: ["transform-object-rest-spread"]
});

let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(z); // { a: 3, b: 4 }

// Spread properties
let n = { x, y, ...z };
console.log(n); // { x: 1, y: 2, a: 3, b: 4 }

I am trying the above example from http://babeljs.io/docs/plugins/transform-object-rest-spread/ and it's not working.

let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
            ^^^
SyntaxError: Unexpected token ...
    at Object.exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:418:7)
    at startup (bootstrap_node.js:139:9)
    at bootstrap_node.js:533:3

If I run it with babel-node then it works fine. Any idea why?


Solution

  • require("babel-core").transform("code", {
      plugins: ["transform-object-rest-spread"]
    });
    

    This is the Node API to transform code given as the first argument of the .transform() function. You would need to replace "code" with the actual code you want to transform. It won't touch any files. You don't do anything with the returned code, but you try to run the rest of the file regularly with Node, which doesn't support object spread operator yet. You would either have to execute the generated code, or write it to a file, which you can run with Node.

    Here is an example how you would transpile your code with the Node API:

    const babel = require('babel-core');
    const fs = require('fs');
    
    // Code that will be transpiled
    const code = `let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
    console.log(x); // 1
    console.log(y); // 2
    console.log(z); // { a: 3, b: 4 }
    
    // Spread properties
    let n = { x, y, ...z };
    console.log(n); // { x: 1, y: 2, a: 3, b: 4 }`
    
    const transformed = babel.transform(code, {
      plugins: ["transform-object-rest-spread"]
    });
    
    // Write transpiled code to output.js
    fs.writeFileSync('output.js', transformed.code);
    

    After running this, you have a file output.js which transformed the object spread. And then you could run it with:

    node output.js
    

    See also babel.transform.

    You're probably not going to use the Node API, unless you want to do some very specific with the code, which is some sort of analysis or transformation, but certainly not running it. Or of course when you integrate it in a tool that needs to transpile the code programmatically.

    If you want to just run code, use babel-node. If you want to just transpile it, use the babel executable.