Array.prototype.values() 未定义 - 在 NodeJS 环境中使用 Babel 转译 ES6
Array.prototype.values() is undefined - using Babel to transpile ES6 in NodeJS environment
我的设置是:
$ babel --version
6.3.15 (babel-core 6.3.15)
$ node --version
v5.1.0
如果这也很重要,请使用 Webstorm 11 IDE。
我正在使用 Babel(js) 转译以下 ES6,并设置了一些日志记录来验证:
Array.from([ 'a', 'b' ].keys());
Array.from([ 'a', 'b' ].values()); // TypeError: ["a","b"].values is not a function
Array.from([ 'a', 'b' ].entries());
可以验证这个v.quickly:
Array.prototype.values === undefined) // true
请注意 keys 和 entries 都存在。
知道可能的原因是什么吗? (我是否错过了一个特殊的选项标志或 Babel 上的一些东西来打开对这个特性的支持?)。感谢您的帮助,同时将继续检查文档等。
为完整性提供答案。 BabelJS 需要一个额外的 polyfill 包来扩展它的一些额外的 ES6+ 特性——比如这个问题中的那个。
npm install babel-polyfill --save
然后在受影响模块的顶部插入以下 require 语句以获得所需的(生成器)行为:
require("babel-polyfill");
这应该是您所需要的,只需导入模块即可添加所需的 polyfill
我知道,您接受了答案,但我强烈建议对 node.js 使用 core-js standard library。
有了这个库,您将忘记在 JS 功能支持方面遇到的任何问题。
它包括 ECMAScript 5、ECMAScript 6 的 polyfill:承诺、符号、集合、迭代器、类型化数组、ECMAScript 7+ 提案、setImmediate 等。一些附加功能,例如字典或扩展的部分应用程序。
安装和使用它很容易:
npm i core-js --save
然后在您的项目中,以这种方式使用它,以包含它支持的所有功能:
// Without global namespace pollution
var core = require('core-js/library');
或者像这样,如果您只想包含特定功能(在您的情况下您缺少 Array.prototype.values()):
require('core-js/fn/array/values');
在我自己发现它之后,这个库对我来说对每个项目都是一个 "must-have"。包说明可以在官方页面找到:https://www.npmjs.com/package/core-js
我的设置是:
$ babel --version
6.3.15 (babel-core 6.3.15)
$ node --version
v5.1.0
如果这也很重要,请使用 Webstorm 11 IDE。
我正在使用 Babel(js) 转译以下 ES6,并设置了一些日志记录来验证:
Array.from([ 'a', 'b' ].keys());
Array.from([ 'a', 'b' ].values()); // TypeError: ["a","b"].values is not a function
Array.from([ 'a', 'b' ].entries());
可以验证这个v.quickly:
Array.prototype.values === undefined) // true
请注意 keys 和 entries 都存在。
知道可能的原因是什么吗? (我是否错过了一个特殊的选项标志或 Babel 上的一些东西来打开对这个特性的支持?)。感谢您的帮助,同时将继续检查文档等。
为完整性提供答案。 BabelJS 需要一个额外的 polyfill 包来扩展它的一些额外的 ES6+ 特性——比如这个问题中的那个。
npm install babel-polyfill --save
然后在受影响模块的顶部插入以下 require 语句以获得所需的(生成器)行为:
require("babel-polyfill");
这应该是您所需要的,只需导入模块即可添加所需的 polyfill
我知道,您接受了答案,但我强烈建议对 node.js 使用 core-js standard library。
有了这个库,您将忘记在 JS 功能支持方面遇到的任何问题。 它包括 ECMAScript 5、ECMAScript 6 的 polyfill:承诺、符号、集合、迭代器、类型化数组、ECMAScript 7+ 提案、setImmediate 等。一些附加功能,例如字典或扩展的部分应用程序。
安装和使用它很容易:
npm i core-js --save
然后在您的项目中,以这种方式使用它,以包含它支持的所有功能:
// Without global namespace pollution
var core = require('core-js/library');
或者像这样,如果您只想包含特定功能(在您的情况下您缺少 Array.prototype.values()):
require('core-js/fn/array/values');
在我自己发现它之后,这个库对我来说对每个项目都是一个 "must-have"。包说明可以在官方页面找到:https://www.npmjs.com/package/core-js