Kenny Kenny - 1 year ago 95
Node.js Question

How to setup node environment to run ES6 codes involving syntax like `import ... from ...`?

I want to run the following codes based on source code here containing some ES6 syntax like

import ... from ...

import rgb from "./rgb";
import array from "./array";
import date from "./date";
import number from "./number";
import object from "./object";
import string from "./string";
import constant from "./constant";

var interpolateValue = function(a, b) {
// set var t and c
var t = typeof b, c;

// if b is null or t is type boolean,
return b == null || t === "boolean" ? constant(b)
: (t === "number" ? number
: t === "string" ? ((c = color(b)) ? (b = c, rgb) : string)
: b instanceof color ? rgb
: b instanceof Date ? date
: Array.isArray(b) ? array
: isNaN(b) ? object
// (a,b) is 2 function args
: number)(a, b);

console.log(interpolateValue("foo", "bar")(0.5));

I tried to run this code inside a node project with
as dependencies. However, I recieved the following error pointing at
in console:

SyntaxError: Unexpected reserved word
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3

my question:

  1. How can I set up a node environment step by step in order to run codes with ES6 syntax?

  1. with help of the first answer, I managed to set up the environment to run successfully (details can be found in the second solution), but the speed of compiling seems slow. Does anyone know why?

Thank you!

Answer Source

Yes you need babel. Have you checked out the documentation here:

$ npm install --save-dev babel-core


require("babel-core").transform("code", options);

after that make sure you've setup your .babelrc file:

  "presets": ["es2015"]

Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download