When packaging with WebPack, we often want to separate third-party libraries and use them as stable versions of the file to reduce the number of requests using the browse cache. There are two common methods for extracting third-party libraries

  • CommonsChunkPlugin
  • DLLPlugin

Difference: in the first way, the third party library should also be packaged once each time. In the second way, only the project files are packaged each time. We only need to reference the third party compressed file that is packaged the first time

CommonsChunkPlugin method introduction

Let’s take Vue for example

const vue = require('vue') {entry: {// bundle is the export name of the project file we want to package, app is the entry js file bundle:'app'// Vendor is the final file name of the third-party library we want to package. In the array, which third-party libraries we want to package. If it is not in node -- modules, you can fill in the specific address of the library vendor: ['vue']
  },
 output: {
     path: __dirname + '/bulid/'// filename filename:'[name].js'}, plugins: {/ / instantiate here webpack.optimize.Com monsChunkPlugin constructor / / are generated after packaging vendor. Js file new monsChunkPlugin (webpack.optimize.Com'vendor'.'vendor.js')}}Copy the code

Then package the generated file into an HTML file

 <script src="/build/vendor.js"></script>
 <script src="/build/bundle.js"></script>
Copy the code

Introduction to the DLLPlugin method

Prepare two files first

  • webpack.config.js
  • webpack.dll.config.js

The webpack.dll.config.js file is configured as follows

const webpack = require('webpack')
const library = '[name]_lib'
const path = require('path')

module.exports = {
  entry: {
    vendors: ['vue'.'vuex']
  },

  output: {
    filename: '[name].dll.js',
    path: 'dist/',
    library
  },

  plugins: [
    new webpack.DllPlugin({
      path: path.join(__dirname, 'dist/[name]-manifest.json'),
      // This must match the output.library option above
      name: library
    }),
  ],
}


Copy the code

The webpack.config.js file is then configured as follows

const webpack = require('webpack')

module.exports = {
  entry: {
    app: './src/index'
  },
  output: {
    filename: 'app.bundle.js',
    path: 'dist/',
  },
  plugins: [
    new webpack.DllReferencePlugin({
      context: __dirname,
      manifest: require('./dist/vendors-manifest.json')]}})Copy the code

Then run

$ webpack --config webpack.dll.config.js
$ webpack --config webpack.config.js
Copy the code

HTML reference mode

<script src="/dist/vendors.dll.js"></script>
<script src="/dist/app.bundle.js"></script>
Copy the code

Refer to the article