将ES7异步/等待与节点,Webpack和babel-loader一起使用时出错 [英] Error using ES7 async/await with node, webpack and babel-loader
问题描述
我正在尝试使用带有webpack和babel-loader(es2015 + stage-0预设)的node.js在服务器上使用javascript ES7语法.我已经将它与babel-node一起使用,但是当我运行webpack时,在async关键字上出现以下错误(9:22在async关键字之后):
I'm trying to use javascript ES7 syntax on the server using node.js with webpack and babel-loader (es2015 + stage-0 presets). I've gotten it to work with babel-node but when I run webpack I get the following error at the async keyword (9:22 is after the async keyword):
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 ,关于如何使它工作的任何想法?
I've put the code on github at https://github.com/qubitron/node-async-sample, any ideas on how to get this to work?
这是src/server.js中的相关代码段:
Here is the relevant snippet from 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:
and 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异步等待功能,其中babel-loader不起作用
I saw a similar issue here but it has a different error message and was fixed in babel:master: ES7 async await functions with babel-loader not working
推荐答案
您的src路径不正确.您绝对不应该(例如从不 :))使用字符串连接来连接路径,其中有 path.join
.
Your src path was incorrect. You should never (like never :)) join pathes using string concatenation there is path.join
for that.
{
test: /\.jsx?$/,
include: path.join(__dirname, 'src'),
loader: 'babel-loader'
}
顺便说一句,这将解决解析问题,但是您仍然需要通过添加相应的扩展名来解析部分并使用json-loader
BTW, this will fix parsing issue but you still gonna need to handle .json
file loading by adding corresponding extension to resolve section and using json-loader
{ test: /\.json$/, loader: 'json-loader' }
此外,您还需要处理缺少模块的警告.例如fs
和net
.
Also you'll need to handle missing modules warning. For example fs
and net
.
因此,我建议您使用 babel-cli
来预编译服务器代码.
So I do recommend you to use babel-cli
to precompile server code.
babel src --out-dir dist
这篇关于将ES7异步/等待与节点,Webpack和babel-loader一起使用时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!