Search code examples
javascriptreactjswebpack-2

Async Code Splitting Webpack - Unexpected Token


I was just following this guide

I have this code:

import React, { PropTypes, Component } from 'react';

import('contact-page').then(() => {});

I get this output: webpack output

This is my webpack file:

var webpack = require('webpack');
var packages = require('./package.json');
var path = require('path');

var ExtractTextPlugin = require("extract-text-webpack-plugin");
var HtmlWebpackPlugin = require('html-webpack-plugin');

var filterDependencies = ['normalize.css', 'font-awesome'];
var dependencies = Object.keys(packages.dependencies).filter(f => !filterDependencies.some(fd => fd === f));


module.exports = {
    entry: {
        main: './src/index.js',
        vendor: dependencies
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist')
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: "vendor",
            minChunks: Infinity,
        }),
        new ExtractTextPlugin("styles.css"),
        new HtmlWebpackPlugin({
            template: 'index.html'
        })
    ],

    module: {
        rules: [
            {
                test: /\.js?$/,
                use: [ 'babel-loader', ],
                exclude: /node_modules/
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader"
                }),
                exclude: /node_modules/
            },
            {
                test: /(\.png|\.jpg|\.otf)$/,
                use: ['file-loader?name=[name].[ext]&publicPath=assets/&outputPath=assets/']
            } 
        ]
    },

    performance: {
        hints: "warning", // enum
        maxAssetSize: 200000, // int (in bytes),
        maxEntrypointSize: 400000, // int (in bytes)
        assetFilter: function (assetFilename) {
            // Function predicate that provides asset filenames
            return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
        }
    },

    devtool: "source-map", // enum

    target: "web", // enum

    stats: "errors-only",

    devServer: {
        proxy: { // proxy URLs to backend development server
            '/api': 'http://localhost:3000'
        },
        contentBase: path.join(__dirname, 'public'), // boolean | string | array, static file location
        compress: true, // enable gzip compression
        historyApiFallback: true, // true for index.html upon 404, object for multiple paths
        hot: true, // hot module replacement. Depends on HotModuleReplacementPlugin
        https: false, // true for self-signed, object for cert authority
        noInfo: true, // only errors & warns on hot reload
        // ...
    }
};

Solution

  • For dynamin import I'm using babel-plugin-syntax-dynamic-import library - https://www.npmjs.com/package/babel-plugin-syntax-dynamic-import

    After installation you have to extend module.rules sets to something like (as long as you want to mix es2015 and react):

    module: {
      rules: [
      {
        test: /\.js?$/,
        use: {
          loader: 'babel-loader',
          options: {
             presets: [['es2015', "react"]],
             plugins: ['syntax-dynamic-import']
          },
        },
        exclude: /node_modules/
      },
    },
    

    It is described in tutorial https://webpack.js.org/guides/code-splitting-async/#usage-with-babel more detailed.