Thursday 13 April 2017

Build javascript async/await with webpack 2 and babel-loader

I'm using webpack 2.3.3 to build my node.js application with async/await javascript syntax. Transpiling is done using babel-loader 6.4.1. My package.json looks like this:

{ (...)
  "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"
  },
  (...)
}

My webpack config uses the transform-async-to-generator plugin with line loaders: ['babel-loader?presets[]=es2015&presets[]=stage-0&presets[]=react&plugins[]=transform-async-to-generator', 'eslint-loader'] in config file 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 ];

When I run npm run build, the build fails on lines containing async function foo(arg) { (...) } with error Parsing error: Unexpected token function.

When I remove the async/await code parts, the builds succeeds.

I've looked at solutions here and here but could not get the build of async/await code to work.

Can anybody help me with this? Thx a lot



via MDH

No comments:

Post a Comment