对象在节点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 }

我正在尝试从http://babeljs.io/docs/plugins/transform-object-rest-spread/中尝试上述示例。

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

如果我使用babel-node运行它,则可以正常工作。知道为什么?

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

这是将代码转换为.transform()函数的第一个参数的节点API。您需要用要转换的实际代码替换"code"。它不会触摸任何文件。您对返回的代码没有任何操作,但是您尝试使用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);

运行此操作后,您将拥有一个文件output.js,该文件会转换对象vrize。然后您可以使用:

运行它
node output.js

另请参见babel.transform。

您可能不会使用节点API,除非您想对代码进行一些非常具体的操作,这是某种分析或转换,但肯定不会运行它。当然,当您将其集成到需要以编程为代码的工具中。

如果您只想运行代码,请使用babel-node。如果您只想将其转移,请使用babel可执行文件。

您可以检查Node.js ES2015支持。nodejs object rest/spread properties受支持表格v8.3。

let person = {id:1, name: 'Mahbub'};
let developer = {...person, type: 'nodeJs'};
let {name, ...other} = {...developer};
console.log(developer); // --> { id: 1, name: 'Mahbub', type: 'nodeJs' } 
console.log(name); // --> Mahbub
console.log(other); // --> { id: 1, type: 'nodeJs' } 

最新更新