Review web Pack: enable the extraction of dev server and common modules

github
Previous articles:
Review webback: skeleton building

Get ready

What problems do dev server need to solve?

  1. Development environment hot module replacement
  2. auto refresh
  3. debug traces to the original file. Source map interpretation

To start dev server, we need to distinguish the production environment from the development environment. Previously, we used to generate the production environment directly. Now we need to use the webpack-merge Make a distinction.

  • npm i dev-server -D
  • Modify package.json
"script": {
  "build": "./build/build.js",
  "dev": "dev-server --config ./build/dev.js"
}
// On the previous basis, we did not need to package css separately in the development environment
/**** base config ****/
const utils = require('./utils')
const path = require('path')
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
module.exports={
  entry:utils.entries(),
  output:{
    filename:'[name].js',
    path:path.resolve(__dirname,'../dist')
  },
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'img/[name].[hash:7].[ext]'
            }
          }
        ]
      },
      {
        test: /\.html$/,
        use: 'html-loader'
      }
    ]
  },
  plugins:[
    new CleanWebpackPlugin(),
  ].concat(utils.htmlPlugins())
}
/**** Production environment build.js****/
const baseConfig = require('./webpack.config')
const webpack = require('webpack')
const merge = require('webpack-merge')
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
const config = merge(baseConfig, {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextWebpackPlugin.extract({
          fallback:'style-loader',
          use:'css-loader'
        })
      }
    ],
  },
  plugins: [
    new ExtractTextWebpackPlugin('css/[name].css')
  ]
})
webpack(config, function(err){
  if (err) throw err
  console.log('product......')
})
  • Configure dev server
/**** dev.js ****/
const baseConfig = require('./webpack.config')
const merge = require('webpack-merge')
const webpack = require('webpack')
const config = merge(baseConfig, {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  // https://segmentfault.com/a/1190000004280859
  // devtool: 'inline-source-map',
  devServer: {
    contentBase: '/',
    // Listening port
    port: 8080,
    // Replace with hot module
    hot: true,
    // Open page automatically
    open: true,
    // Show packaging progress
    progress: true,
    // Error report printed on the page
    overlay: { 
      warnings: false,
      errors: true
    },
    // watchOptions: {
    //   //Delay refresh after file change, poll in milliseconds.
    //   poll: 5000
    //   // 
    //   aggregateTimeout: 1000
    // }
  },
  plugins: [
  // Load hot module replacement package
    new webpack.HotModuleReplacementPlugin()
  ]
})
module.exports = config

//  package.json
-  "dev": "dev-server --config ./build/dev.js"
+  "dev": "dev-server --config ./build/dev.js --inline" // Real time update
// It is a puzzle that the inline configuration does not work in devServer, but is feasible in command

Extraction of common modules

Code separation is one of the most attractive features in Web pack. This feature can separate the code into different bundles, and then load these files on demand or in parallel. Code separation can be used to get smaller bundles and control the loading priority of resources. If it is used properly, it will greatly affect the loading time.
code separation

/**** build.js ****/
// Equivalent to extracting common modules for each entry file
+ const utils = require('./utils')
+ new webpack.optimize.CommonsChunkPlugin({
+     name: 'common',
+     filename: 'common/[name].bundle.js',
+     minChunks: utils.htmlPlugins().length
+ }),
/**** utils.js ****/
let conf = {
    filename:filename+'.html',
    template:path.resolve(PAGE_PATH,filename+'/'+filename+'.html'),
-   chunks:[filename]
+   chunks:[filename, 'common']
    inject:true,
 }

Finally, more details can be tried from clone on my github~~

github

Tags: Webpack github JSON npm

Posted on Fri, 01 May 2020 00:47:40 -0700 by seany123