The Use of Chain Webpack in vue-cli

Preface

In the project development, we will inevitably encounter the situation that we need to change the configuration of webpack. Today, we will mainly talk about some configuration changes in vue.config.js, briefly introduce the use of loader; simple configuration with configure Webpack; advanced configuration with chain Webpack; including the addition, modification of loader; and Configuration of plug-ins

1. First, a brief introduction to the simple use of loader in Web pack is given.

Loader: webpack is used to pre-process modules. Before a module is introduced, loader is used to process the contents of the module in advance. When you package, loader is needed to process some content, such as css module. By default, webpack only handles js code, so when we want to package other content, we need to do so. To have the corresponding loader handle some content
Usage method:
In the configuration file, webpack.config.js adds a module attribute, which is an object, in which there is a rules field, first coded

module:{
        rules:[{
            test:/\.js$/,
            use:[{
                loader:'babel-loader',
                options: {
                presets: [
                  "es2015", "react"
                ],
                plugins: ["syntax-dynamic-import"]
          }
            }]
        }]
    }

Rules is an array in which all your loader configurations can be written. Each loader configuration is an object that matches different rules.
test:test is followed by a regular expression that matches different file types.
Use: In this rule, when you match this file, you need to use the corresponding loader to process this type of file. User receives an array, which means that when he matches the file, it can enable a lot of loaders to process the content of the file.
If you use the default configuration of loader, you can write use:['css-loader','style-loader'];
If additional configurations are needed, they need to be written as objects, and configurations are written in options.

Of course, there are some other attributes (exclude, include, etc.), which will not be discussed in detail here.
Before you use these loader s, you need to install these packages with npm.

2. Simple configuration with configure Web pack;

/ vue.config.js
module.exports = {
  configureWebpack: {
    plugins: [
      new MyAwesomeWebpackPlugin()
    ]
  }
}

This object will be merged into the final web pack configuration by webpack-merge.
If you need to configure behavior conditionally based on the environment, or if you want to modify the configuration directly, replace it with a function (which will be lazily executed after the environment variable is set). The first parameter of the method receives the parsed configuration. Within the function, you can modify the configuration directly or return an object that will be merged:

// vue.config.js
module.exports = {
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      // Modify configuration for production environment.
    } else {
      // Modify the configuration for the development environment.
    }
  }
}

3. Advanced Configuration with Chain Webpack

The web pack configuration within Vue CLI is maintained through webpack-chain. This library provides an upper level abstraction of the original configuration of webpack, enabling it to define named loader rules and named plug-ins, and to have the opportunity to enter these rules at a later stage and modify their options.

It allows us to control its internal configuration more finely. Next, there are some common examples of chain Webpack modifications in vue.config.js.
Official documents give me some simple examples:
Modify the Loader option

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('vue')
      .use('vue-loader')
        .loader('vue-loader')
        .tap(options => {
          // Modify its options...
          return options
        })
  }
}

Add a new Loader

// vue.config.js
module.exports = {
  chainWebpack: config => {
    // GraphQL Loader
    config.module
      .rule('graphql')
      .test(/\.graphql$/)
      .use('graphql-tag/loader')
        .loader('graphql-tag/loader')
        .end()
  }
}

Replace Loader in a rule.

// Add svg-sprite-loader
    const svgRule = config.module.rule('svg')
    svgRule.uses.clear()
    svgRule
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .tap(options => {
        options = {
          symbolId: 'icon-[name]'
        }
        return options
      })

Modifying the code of the plug-in can be seen in the following examples.
First of all, the code, today we mainly talk about the configuration of the project, the configuration of the api address: https://cli.vuejs.org/zh/conf...

const path = require('path')
const webpack = require('webpack')
module.exports = {
  // Modify output.path
  outputDir: 'dist',
  // Modify output.publishPath
  publishPath: './',
  chainWebpack: config => {
    // Add global scss file
    const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
    types.forEach(type => { //Match to all files that need to be imported
      config.module.rule('scss').oneOf(type).use('style-resource')
        .loader('style-resources-loader')
        .options({
          patterns: [
            path.resolve(__dirname, 'src/css/base.scss')
          ]
        })
    })
    // Add svg-sprite-loader
    const svgRule = config.module.rule('svg')
    svgRule.uses.clear()
    svgRule
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .tap(options => {
        options = {
          symbolId: 'icon-[name]'
        }
        return options
      })
    // Remove prefetch plug-in//preload
    config.plugins.delete('prefetch')
    // Introduce
    const chunkFolder = process.env.NODE_ENV !== 'production' ? 'debug' : 'dist'
    config.plugin('dll-reference-plugin')
      .use(webpack.DllReferencePlugin)
      .tap(options => {
        options[0] = {
          context: __dirname,
          manifest: require(path.join(__dirname, `./src/common_chunk/${chunkFolder}/manifest.json`))
        }
        return options
      })
    config.plugin('add-asset-html-webpack-plugin')
      .use('add-asset-html-webpack-plugin')
      .tap(options => {
        options[0] = {
          filepath: path.resolve(__dirname, `./src/common_chunk/${chunkFolder}/lib_*.js`)
        }
        return options
      })
  }
}

The above code uses style-resources-loader, which can import files automatically.
DllReference Plugin is a plug-in that allows third-party code to be packaged separately from our own code to speed up packaging; it needs to be used with the add-asset-html-webpack-plugin plug-in;
After packaging with this plug-in, the tool library is generated under the src/common_chunk folder, the third-party dependencies are packaged into a file, and an index manifest.json file for all library codes is generated.

ps: Another way to introduce common style files globally, so that they can be used directly.

module.exports = {
  // ...
  css: {
    loaderOptions: {
      sass: {
        // Adjust the location of the file according to your own style
        data: `@import "@src/css/base.scss";`
      }
    }
  }
};

Documents referenced in this article: https://cli.vuejs.org/zh/guid...

Tags: Javascript Webpack Vue JSON Attribute

Posted on Tue, 30 Jul 2019 01:32:16 -0700 by hoffmeister