问题
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)
I've put the code on github at https://github.com/qubitron/node-async-sample, any ideas on how to get this to work?
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"
]
}
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'
}
]
}
};
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
回答1:
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'
}
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' }
Also you'll need to handle missing modules warning. For example fs
and net
.
So I do recommend you to use babel-cli to precompile server code.
babel src --out-dir dist
来源:https://stackoverflow.com/questions/38067405/error-using-es7-async-await-with-node-webpack-and-babel-loader