使用webpack 2和babel-loader构建javascript async / await

时间:2017-04-13 23:33:50

标签: node.js webpack async-await babel-loader

我正在使用webpack 2.3.3使用async / await javascript语法构建我的node.js应用程序。使用babel-loader 6.4.1完成透明化。 我的package.json看起来像这样:

{ (...)
  "scripts": {
    "build": "rm -Rf dist; webpack -p --progress --colors --display-error-details --config webpack/prod.js",
    "postinstall": "npm run build",
    "start": "node dist/assets/server.js"
  },
  (...)
  "dependencies": {
    "babel-cli": "6.24.1",
    "babel-core": "6.24.1",
    "babel-loader": "6.4.1",
    "babel-plugin-transform-async-to-generator": "6.24.1",
    "babel-polyfill": "6.23.0",
    "babel-preset-es2015": "6.24.1",
    "babel-preset-react": "6.24.1",
    "babel-preset-stage-0": "6.24.1",
    "babel-preset-stage-1": "6.24.1",
    "eslint": "3.19.0",
    "eslint-loader": "1.7.1",
    "eslint-plugin-react": "6.10.3",
    (...)
    "webpack": "2.3.3"
  },
  (...)
}

我的webpack配置在配置文件transform-async-to-generator中使用loaders: ['babel-loader?presets[]=es2015&presets[]=stage-0&presets[]=react&plugins[]=transform-async-to-generator', 'eslint-loader']插件和行webpack/prod.js

'use strict';

require('babel-polyfill');
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');

var nodeModules = {};

fs.readdirSync('node_modules')
    .filter(function(x) {
        return ['.bin'].indexOf(x) === -1;
    })
    .forEach(function(mod) {
        nodeModules[mod] = 'commonjs ' + mod;
    });

var serverConfig = {
    entry: ['babel-polyfill', './src/server'],
    target: 'node',
    externals: nodeModules,
    output: {
        path: path.resolve(__dirname, '../dist/assets/'),
        filename: 'server.js'
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: { warnings: false }
        })
    ],
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                loaders: ['babel-loader?presets[]=es2015&presets[]=stage-0&presets[]=react&plugins[]=transform-async-to-generator', 'eslint-loader'],
                exclude: /node_modules/
            }
        ]
    }
};

module.exports = [ clientConfig, serverConfig ];

当我运行npm run build时,构建在包含错误async function foo(arg) { (...) }的{​​{1}}的行上失败。

当我删除async / await代码部分时,构建成功。

我查看了解决方案herehere,但无法使async / await代码的构建工作。

有人可以帮我这个吗?很多

1 个答案:

答案 0 :(得分:2)

解析错误发生在eslint-loader中,因为默认的eslint解析器无法理解asyncawait。您必须按照Specifying Parser中的说明使用babel-eslint。在你的eslint配置中添加:

"parser": "babel-eslint"

并安装babel-eslint

npm install --save-dev babel-eslint