Skip to content

Instantly share code, notes, and snippets.

@jasonphillips
Last active October 30, 2017 19:01
Show Gist options
  • Save jasonphillips/57c1f8f9dbcd8b489dafcafde4fcdba6 to your computer and use it in GitHub Desktop.
Save jasonphillips/57c1f8f9dbcd8b489dafcafde4fcdba6 to your computer and use it in GitHub Desktop.
babel error with Set() and spread syntax, when using "loose":true
{
"presets": [["env", {
"loose": true
}
]]
}
{
"name": "test-babel-set-spread",
"version": "1.0.0",
"description": "",
"scripts": {
"test:node": "node test-set-spread.js",
"test:babel": "babel test-set-spread.js | node",
"build:babel": "babel test-set-spread.js -o test-set-spread.babel.js"
},
"license": "ISC",
"dependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1"
}
}
'use strict';
var priorSet = new Set(['a', 'b']);
console.log('prior Set:', priorSet);
var withSpread = new Set([].concat(priorSet, ['e']));
console.log('with spread syntax:', withSpread);
var withArrayFrom = new Set(Array.from(priorSet).concat(['e']));
console.log('with Array.from:', withArrayFrom);
const priorSet = new Set(['a','b']);
console.log('prior Set:', priorSet);
const withSpread = new Set([...priorSet, 'e']);
console.log('with spread syntax:', withSpread);
const withArrayFrom = new Set(Array.from(priorSet).concat(['e']));
console.log('with Array.from:', withArrayFrom);

$: npm install

$: npm run test:node

prior Set: Set { 'a', 'b' }
with spread syntax: Set { 'a', 'b', 'e' }
with Array.from: Set { 'a', 'b', 'e' }

$: npm run test:babel

prior Set: Set { 'a', 'b' }
with spread syntax: Set { Set { 'a', 'b' }, 'e' }
with Array.from: Set { 'a', 'b', 'e' }

@jasonphillips
Copy link
Author

Demonstrates a syntax issue when compiling code using babel-env and setting loose option to true.

test-rest-spread.js - original syntax
test-rest-spread.babel.js - when compiled with babel

The demonstrations above (npm run test:node / npm run test:babel) illustrate that the output is not equivalent when running the original code or the code produced by babel.

This line is the issue; it works normally within node, and creates a new Set containing the prior Set and an added value:

const withSpread = new Set([...priorSet, 'e']);

But when processed via babel and loose:true, it becomes this:

var withSpread = new Set([].concat(priorSet, ['e']));

Which ends up creating a new Set() containing the prior one as an element, instead of spreading its contents.

@jasonphillips
Copy link
Author

The final line of the code shows an alternative syntax which will pass through babel unharmed, and will work on either end:

const withArrayFrom = new Set(Array.from(priorSet).concat(['e']));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment