【问题标题】:Object spread not working in Node 7.5对象传播在 Node 7.5 中不起作用
【发布时间】:2017-03-02 23:56:07
【问题描述】:
// 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 运行它,那么它工作正常。知道为什么吗?

【问题讨论】:

  • 你不能把你的 babel 调用和带有实验特性的代码放在同一个文件中?!对于 babel-node,你把那个插件放在配置文件中
  • 那么我应该如何构建这个?如果这是我的 index.js
  • 您说使用 babel-node 运行时效果很好。那么你的目标是什么?

标签: node.js babeljs babel-node


【解决方案1】:
require("babel-core").transform("code", {
  plugins: ["transform-object-rest-spread"]
});

这是用于转换作为.transform() 函数的第一个参数给出的代码的Node API。您需要将"code" 替换为您要转换的实际代码。它不会触及任何文件。您不对返回的代码执行任何操作,但您尝试使用 Node 定期运行文件的其余部分,Node 尚不支持对象扩展运算符。您要么必须执行生成的代码,要么将其写入文件,您可以使用 Node 运行该文件。

这是一个如何使用 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,它改变了对象传播。然后你可以运行它:

node output.js

另见babel.transform

您可能不会使用 Node API,除非您想对代码做一些非常具体的操作,即某种分析或转换,但肯定不会运行它。或者当然,当您将它集成到需要以编程方式转换代码的工具中时。

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

【讨论】:

    【解决方案2】:

    您可以查看Node.js ES2015 Supportv8.3 支持 Nodejs object rest/spread properties

    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' } 
    

    【讨论】:

      猜你喜欢
      • 2017-09-30
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多