Robert Brax Robert Brax - 6 months ago 33
Javascript Question

Can't run babel transpiled files with node

Here is the very basic express boilerplate code that I just modified to use es6 import in order to test the transpiling process app.js:

import "babel-polyfill";
import * as express from "express"
var app = express();


app.get('/', function (req, res) {
res.send('Hello World!');
});

app.listen(3000, function () {
console.log('Examdple app listening on port 3000!');
});


in .babelrc

{
"presets": [
"es2015"
],
"plugins": ["transform-runtime",
"transform-es2015-classes"]
}


Resulting transpiled code app-compiled.js:

"use strict";

require("babel-polyfill");

var _express = require("express");

var express = _interopRequireWildcard(_express);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

var app = express();

app.get('/', function (req, res) {
res.send('Hello World!');
});

app.listen(3000, function () {
console.log('Examdple app listening on port 3000!');
});

//# sourceMappingURL=app-compiled.js.map


Now trying to run /usr/local/bin/node app-compiled.js :

var app = express();
^
TypeError: express is not a function


or /usr/local/bin/node app.js

/Users/Documents/Apps_And_Sites/Js_Apps/projectname/app.js:1
(function (exports, require, module, __filename, __dirname) { import "babel-polyfill";
^^^^^^

SyntaxError: Unexpected reserved word


Also, when I don't use the polyfill it's the same 'import' error without the encapsulating function.

If this helps, dependencies in package.json:

"devDependencies": {
"babel-cli": "^6.9.0",
"babel-core": "^6.9.1",
"babel-eslint": "^6.0.4",
"babel-plugin-syntax-flow": "^6.8.0",
"babel-plugin-transform-class-properties": "^6.9.1",
"babel-plugin-transform-flow-strip-types": "^6.8.0",
"babel-plugin-transform-runtime": "^6.9.0",
"babel-polyfill": "^6.9.1",
"babel-preset-es2015": "^6.9.0",
"eslint-plugin-flowtype": "^2.2.7",
"flow-bin": "^0.26.0"
},
"dependencies": {
"babel-runtime": "^6.9.2",
"express": "^4.13.4"
}
}


In my webstorm ide, I have babel set with these parameters:


Program: node_modules/babel-cli/bin/babel.js

Arguments: --source-maps --out-file
$FileNameWithoutExtension$-compiled.js $FilePath$

Output paths to refresh:
$FileNameWithoutExtension$-compiled.js:$FileNameWithoutExtension$-compiled.js.map


Why can't node run the babel transpiled code ?

Answer

Your import is wrong, it should just be:

import express from 'express';
Comments