Tree Shaking

  1. css Tree Shaking
yarn add purify-css purifycss-webpack -D
const glob = require('glob')
const PurifyCSSPlugin = require('purifycss-webpack'Paths: glob.sync(path.join(__dirname,)) //'pages/*/*.html'))})]Copy the code
  1. Js optimization
yarn add webpack-parallel-uglify-plugin -D
const WebpackParallelUglifyPlugin = require('webpack-parallel-uglify-plugin')
plugins: [
new WebpackParallelUglifyPlugin({
      uglifyJS: {
        output: {
          beautify: false// No need to format comments:false// do not keep comments}, compress: {warnings:falseDrop_console: // UglifyJs does not print a warning when deleting code that is not used:trueCollapse_vars // Delete all 'console' statements as collapse_varstrue// Inline variable reduce_vars that are defined but used only once:true// Extract static values that occur multiple times but are not defined as variables to reference}}})]Copy the code

Extract common code

Large sites have multiple pages, each containing many common code links due to the same technology stack and style code

Optimization: {splitChunks: {cacheGroups: {Commons: {chunks:'initial',
          minChunks: 2,
          maxInitialRequests: 5, // The default limit is too small to showcase the effect
          minSize: 0, // This is example is too small to create commons chunks
          name: 'common'}}}},Copy the code

Package third-party class libraries

  1. DllPlugin plugin: used to package one dynamic link library after another
  2. DllReferencePlugin: Introduce the DllPlugin plugin wrapped dynamic connection library into the configuration file
In the package. In json"scripts": {
    "build": "webpack --mode development"."build:dll": "webpack --config webpack.dll.config.js --mode development"."dev": "webpack-dev-server --open --mode development"} create webpack.dll.config.js const path = require('path')
const webpack = require('webpack') /** * Minimize the search scope * target:'_dll_[name]'Exports = {entry: {vendor: ['jquery'.'lodash']
   },
   output: {
     path: path.join(__dirname, 'static'),
     filename: '[name].dll.js',
     library: '_dll_[name]'Plugins: [new webpack.dllplugin ({name:}); // Manifest is a file that describes plugins: [new webpack.dllplugin ({name:});'_dll_[name]',
       path: path.join(__dirname, 'manifest.json')})]} in webpack. Config. Plugins in js: [new webpack. DllReferencePlugin ({manifest: path. Join (__dirname,'manifest.json'})] Execute NPM run build: DLL to pack third-party packagesCopy the code

Using happypack

HappyPack allows Webpack to split tasks into multiple sub-processes for concurrent execution, which then send the results to the main process. happypack

npm i happypack@next -D
const HappyPack = require('happypack')
const os = require('os')
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length })

  {
    test: /\.js$/,
    // loader: 'babel-loader',
    loader: 'happypack/loader? id=happy-babel-js'// Add new HappyPack build loader include: [resolve()'src')],
    exclude: /node_modules/,
  }
  
  plugins: [
    new HappyPack({
      id: 'happy-babel-js',
      loaders: ['babel-loader? cacheDirectory=true'],
      threadPool: happyThreadPool
    })
]
Copy the code

Show packing time

yarn add progress-bar-webpack-plugin -D
const ProgressBarPlugin = require('progress-bar-webpack-plugin')
plugins: [
    new ProgressBarPlugin({
      format: ' build [:bar] ' + chalk.green.bold(':percent') + ' (:elapsed seconds)'})]Copy the code

Multipage configuration

Git complete code link

Entry: {// Entry is a string or array that has a single page, or an object that has multiple pages. Here is the index page and the base page index:'./pages/index/index.js',
    base: './pages/base/base.js'} plugins: [new HtmlWebpackPlugin({template:'./pages/index/index.html',
      filename: 'pages/index.html'.hash: true,
      chunks: ['index'.'common'],
      minify: {
        removeAttributeQuotes: true
      }
    }),
    new HtmlWebpackPlugin({
      template: './pages/base/base.html',
      filename: 'pages/base.html'.hash: true,
      chunks: ['base'.'common'],
      minify: {
        removeAttributeQuotes: true}}),]Copy the code

Complete multi-page configuration code git complete code link

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
const Webpack = require('webpack')
const glob = require('glob')
const PurifyCSSPlugin = require('purifycss-webpack') / /let cssExtract = new ExtractTextWebpackPlugin('static/css/[name].css')

module.exports = {
  entry: {
    index: './pages/index/index.js',
    base: './pages/base/base.js'
  },
  output: {
    path: path.join(__dirname, 'dist'), // name is the name of entry main,hashIt is calculated based on the contents of the packaged filehashValue filename:'static/js/[name].[hash].js',
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.css$/, 
        use: ExtractTextWebpackPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader'.'postcss-loader']})}, {test: /\.js$/,
        use: {
          loader: 'babel-loader',
          query: {
            presets: ['env'.'stage-0'.'react'] 
          }
        }
      }
    ]
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          chunks: 'initial',
          minChunks: 2,
          maxInitialRequests: 5, // The default limit is too small to showcase the effect
          minSize: 0, // This is example is too small to create commons chunks
          name: 'common'
        }
      }
    }
  },
  plugins: [
    new CleanWebpackPlugin([path.join(__dirname, 'dist')]),
    new HtmlWebpackPlugin({
      template: './pages/index/index.html',
      filename: 'pages/index.html'.hash: true,
      chunks: ['index'.'common'],
      minify: {
        removeAttributeQuotes: true
      }
    }),
    new HtmlWebpackPlugin({
      template: './pages/base/base.html',
      filename: 'pages/base.html'.hash: true,
      chunks: ['base'.'common'],
      minify: {
        removeAttributeQuotes: true
      }
    }),
    new ExtractTextWebpackPlugin({
      filename: 'static/css/[name].[hash].css'}), new PurifyCSSPlugin({// Paths: glob.sync(path.join(__dirname,'pages/*/*.html'))
    })
  ],
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    port: 9090,
    host: 'localhost',
    overlay: true,
    compress: true// Whether to enable gzip compression when the server returns to the browser}}Copy the code

Vue-cli several important paths

AssetsSubDirectory (static) The rest of the JS, IMG, CSS is in assetsPublicPath: project directory a bar (/)Copy the code

To be continued: NEXT, I will rebuild a project based on VUe-CLI, single page and multiple pages will be available!! Let you understand vuE-CLI, and can customize the development environment!!