Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.prototype.values() is undefined - using Babel to transpile ES6 in NodeJS environment

My setup is:

$ babel --version
6.3.15 (babel-core 6.3.15)
$ node --version
v5.1.0

Using Webstorm 11 IDE in case that is important too.

I am using Babel(js) to transpile the following ES6, and have set up some logging to verify:

Array.from([ 'a', 'b' ].keys());
Array.from([ 'a', 'b' ].values());  // TypeError: ["a","b"].values is not a function
Array.from([ 'a', 'b' ].entries());

Can verify this v.quickly:

Array.prototype.values === undefined) // true

Note that keys, and entries both exist.

Any ideas what the likely cause is? (Have I missed a special options flag or something on Babel to switch on support of this feature?). Thanks for any help, and shall continue to check documentation etc in meantime.

like image 372
arcseldon Avatar asked Mar 13 '23 23:03

arcseldon


2 Answers

Providing an answer for completeness. BabelJS requires an extra polyfill package to extend it with some extra ES6+ features - such as the one in this question.

npm install babel-polyfill --save

Then insert the following require statement towards the top of the affected module to obtain required (generator) behaviour:

require("babel-polyfill");

This should be all you need, just importing the module adds required polyfill

like image 185
arcseldon Avatar answered Apr 24 '23 01:04

arcseldon


I know, you accepted the answer, but I'd highly recommend to use core-js standard library for node.js.

With this library you'll forget seeing any problems on JS features support. It includes polyfills for ECMAScript 5, ECMAScript 6: promises, symbols, collections, iterators, typed arrays, ECMAScript 7+ proposals, setImmediate, etc. Some additional features such as dictionaries or extended partial application.

It's easy to install dependency and to use it:

npm i core-js --save

Then within your project, use it this way, to include all the features it support:

// Without global namespace pollution 
var core = require('core-js/library');

Or like this, if you want to include only specific features (in your case you was missing Array.prototype.values()):

require('core-js/fn/array/values');

This lib is a "must-have" to me for every project, after I discovered it for myself. Package description can be found at official page: https://www.npmjs.com/package/core-js

like image 36
Farside Avatar answered Apr 24 '23 01:04

Farside