2017-03-02 49 views
-1
// 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/上面的例子,它不工作。對象傳播不工作在節點7.5

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運行它,那麼它工作正常。任何想法爲什麼?

+0

你不能把你的babel調用與具有實驗功能的代碼放在同一個文件中?對於babel-node,你將該插件放在配置文件 – Bergi

+0

中,那麼我應該如何構造它?如果這是我的index.js – cherhan

+0

你說它在babel-node運行時工作正常。那麼你的目標是什麼? – Bergi

回答

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

這是節點API來轉換作爲.transform()函數的第一個參數給出的代碼。您需要用您想要轉換的實際代碼替換"code"。它不會觸及任何文件。您不會對返回的代碼做任何事情,但您會嘗試使用不支持對象擴展操作符的Node定期運行文件的其餘部分。您將不得不執行生成的代碼,或者將其寫入可以使用Node運行的文件。

下面是一個例子,你會如何transpile你的代碼節點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其轉換的對象蔓延。然後你可以運行它:

node output.js 

另請參見babel.transform

您可能不打算使用Node API,除非您想對代碼做一些非常具體的操作,這是某種分析或轉換,但肯定不會運行它。當然,當你將它集成到需要以編程方式編譯代碼的工具中時。

如果您只想運行代碼,請使用babel-node。如果您只想對其進行轉儲,請使用babel可執行文件。

0

你可以檢查Node.js ES2015 Support。 Node_s 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' }