这是我刚刚修改为使用es6导入以测试转换过程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"]
}
结果转换代码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
现在尝试运行/ usr / local / bin / node app-compiled.js:
var app = express();
^
TypeError: express is not a function
或/ 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
另外,当我不使用polyfill时,没有封装功能就会出现相同的'import'错误。
如果这有帮助,请参阅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"
}
}
在我的webstorm ide中,我使用这些参数设置了babel:
程序:node_modules / babel-cli / bin / babel.js
参数: - source-maps --out-file $ FileNameWithoutExtension $ -compiled.js $ FilePath $
要刷新的输出路径: $ $ FileNameWithoutExtension -compiled.js:$ $ FileNameWithoutExtension -compiled.js.map
为什么节点不能运行babel转换代码?
答案 0 :(得分:3)
您的import
在语法上是正确的,但对您的使用有误,它应该是:
import express from 'express';