我正在尝试在服务器上使用 javascript ES7 语法,使用带有 webpack 和 babel-loader(es2015 + stage-0 预设)的 node.js。我已经让它与 babel-node 一起工作,但是当我运行 webpack 时,我在 async 关键字处收到以下错误(9:22 在 async 关键字之后):
ERROR in ./src/server.js Module parse failed: C:\dev\node-async-sample\src\server.js
Unexpected token (9:22) You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (9:22)
我已将代码放在 github 上 https://github.com/qubitron/node-async-sample ,关于如何让它发挥作用的任何想法?
这是来自 src/server.js 的相关片段:
import express from 'express';
import http from 'request-promise';
let server = express();
server.get('/', async function(request, response) {
let result = await http('http://www.google.com');
response.send(result);
});
.babelrc:
{
"presets": [
"es2015",
"node5",
"stage-0"
],
"plugins": [
"transform-runtime"
]
}
和 webpack.config.js:
module.exports = {
entry: [
'babel-polyfill',
'./src/server.js'
],
output: {
path: __dirname + '/dist',
filename: 'server_bundle.js'
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: __dirname + '/src',
loader: 'babel-loader'
}
]
}
};
我在这里看到了类似的问题,但它有不同的错误消息,并已在 babel:master 中修复: ES7 async await functions with babel-loader not working
最佳答案
您的 src 路径不正确。你永远不应该(比如 never :))使用字符串连接加入路径有 path.join
为此。
{
test: /\.jsx?$/,
include: path.join(__dirname, 'src'),
loader: 'babel-loader'
}
顺便说一句,这将解决解析问题,但您仍然需要通过添加相应的扩展来解析部分并使用 json-loader
来处理 .json
文件加载
{ test: /\.json$/, loader: 'json-loader' }
您还需要处理丢失的模块警告。例如 fs
和 net
。
所以我推荐你使用babel-cli
预编译服务器代码。
babel src --out-dir dist
关于javascript - 将 ES7 async/await 与 Node 、webpack 和 babel-loader 一起使用时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38067405/