Demo11:代码分割+ bundle-loader.

基本上同demo10的配置,不同在于入口main.js下用了babel-loader引入

// main.js

// Now a.js is requested, it will be bundled into another file
const load = require('bundle-loader!./a.js'); //a.js会被打包到另一个1.bundle.js中

// To wait until a.js is available (and get the exports)
//  you need to async wait for it.//这里异步调用
load(function(file) {
  document.open();
  document.write('<h1>' + file + '</h1>');
  document.close();
});

Demo12: Common chunk

简单来说就是当有多个打包的文件时, 可以使用CommonsChunkPlugin将公共部分提取到单独的文件中,这对于浏览器缓存和节省带宽很有用。

按照阮一峰老师demo配置就行了,但是有一点会报错,如下:

// webpack.config.js
...
plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: "commons",
      // (the commons chunk name)

      filename: "commons.js",
      // (the filename of the commons chunk)
    })
  ]

这里会报这个错:

webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead.

就是webpack4更新后移除了这个 CommonsChunkPlugin ,用 optimization 来替代了,所以上述plugins应该改为

http:// https://webpack.js.org/plugins/split-chunks-plugin/

Since webpack v4, the CommonsChunkPlugin was removed in favor of optimization.splitChunks.

 optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          name: 'commons',
          chunks: 'initial',
          minChunks: 2
        } } } }

注:optimization与entry,output,plugins是同级,所以这里直接将plugins那段覆盖。

Demo13: Vendor chunk 第三方库打包

  • webpack.config.js
// webpack.config.js
const webpack = require('webpack')
const path = require('path')
module.exports = {
  entry: {
    app: './main.js'
  },
  output: {
    filename: 'bundle.js',
    path: path.join(__dirname)
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    })
  ]
}

使用阮一峰老师demo13的第二种方法配置,因为CommonsChunkPlugin被移出了。

Demo14: Exposing global variables 

如果要使用某些全局变量,并且不想将它们包含在Webpack捆绑包中,则可以启用externals字段。webpack.config.js

// webpack.config.js
module.exports = {
  entry: './main.jsx',
  output: {
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js[x]?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['es2015', 'react']
          }}}]},
  externals: {
    // require('data') is external and available
    //  on the global var data
    data: 'data'}}
// main.jsx
var data = require('data');
var React = require('react');
var ReactDOM = require('react-dom');

ReactDOM.render(
  <h1>{data}</h1>,
  document.body
);
//data.js
const data = 'Hello Webpack 4'
//index.html
<html>
    <body>
      <script src="data.js"></script>
      <script src="./dist/bundle.js"></script>
    </body>
    </html>

注意,Webpack只会构建bundle.js,而不会构建data.js。 我们可以将其公开data为全局变量。

也可以把reactreact-domexternals,这将大大减少build时间和打包成 bundle.js 的大小。

Demo15: React router

直接按demo配置就行- -


爬。