gpt4 book ai didi

javascript - 无法使用 Node 运行 babel 转译文件

转载 作者:行者123 更新时间:2023-11-30 11:57:21 25 4
gpt4 key购买 nike

这是我刚刚修改为使用 es6 import 以测试 app.js 的转译过程的非常基本的 express 样板代码:

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!');
});

在 .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 时,它会出现相同的“导入”错误,但没有封装函数。

如果这有帮助,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:

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

为什么 Node 不能运行 babel 转译后的代码?

最佳答案

您的 import 在语法上是正确的,但对于您的用法是错误的,它应该只是:

import express from 'express';

关于javascript - 无法使用 Node 运行 babel 转译文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37564494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com