如何在webpack 4中使用动态导入和入口点代码拆分

时间:2018-06-25 14:31:34

标签: javascript reactjs webpack webpack-4 code-splitting

在我的项目中,我使用了webpack 4和babel。
我使用动态导入import()通过react-router

加载路由组件

weback的期望输出:

  • vendor.bundle.js:包含特定的主要供应商
    [ 'babel-polyfill', 'react', 'react-dom', 'redux', 'redux-thunk', 'moment', ]
  • main.bundle.js:入口点包
  • 从动态导入生成的每个页面的捆绑包

我当前的webpack配置:

const webpack = require('webpack');
const rootPath = process.cwd();
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: {
    vendor: [
      'babel-polyfill',
      'react',
      'react-dom',
      'redux',
      'redux-thunk',
      'moment',
    ],
    main: ['./client/src/index.jsx'],
  },
  output: {
    filename: '[name].bundle.js',
    chunkFilename: '[name].bundle.js',
    publicPath: '/',
  },
  devtool: 'source-map',

  module: {
    rules: [
      // compile js
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['react', 'es2015', 'stage-2'],
            plugins: ['react-hot-loader/babel'],
            babelrc: false,
          },
        },
      },
      // compile sass
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'resolve-url-loader', 'sass-loader?sourceMap'],
      }, 
      {
        test: require.resolve('blueimp-file-upload'),
        loader: 'imports-loader?define=>false',
      },
    ],
  },

  resolve: {
    extensions: ['.js', '.jsx'],
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({
      inject: true,
      template: `${rootPath}/client/index.html`,
    }),
    new webpack.ProvidePlugin({
      jQuery: 'jquery',
      $: 'jquery',
      jquery: 'jquery',
    }),
  ],
  devServer: {
    hot: true,
    inline: true,
    contentBase: './client',
    port: 6000,
    host: '0.0.0.0',
    historyApiFallback: true,
    disableHostCheck: true,
  },
};

但这会产生:
 * main.bundle.js包含所有供应商的react,react-dom等...
 *和vendor.bundle.js也包含供应商的react,react-dom等...
 * home.bundle.js和其他页面以及自动生成的供应商vendors~Article~NewArticle.bundle.jsvendors~Profile/index.bundle.js

如何避免任何代码重复?

0 个答案:

没有答案