1. Why split configuration files

In our development process, we often configure a lot of things in the webpack.config.js file, both in development and production environments. But when we package in production, there are a lot of configurations that we don’t need in development. So when we write all the configuration in one file, it’s not safe.

So we need to extract the configuration file.

2. The implementation of

We need to install the WebPack-Merge plug-in

 npm install webpack-merge --save-dev
Copy the code

The configuration file is then split into three files: base.config, pron. Config, and dev. Config

Its role as

Base. config: Common configuration extraction part

Pron. config: configuration related to the production environment

Dev. Config: configures the development environment

Next we can use merge to merge configuration files:

The code for the dev.config.js file

const webpackmerge = require('webpack-merge');
const baseConfig = require('./base.config');

module.exports = webpackmerge(baseConfig, {
  devServer: {
    contentBase: path.resolve(__dirname, 'build'),
    inline: true.open: true}})Copy the code

Prod.config. js file code

const webpackmerge = require('webpack-merge');
const baseConfig = require('./base.config');

module.exports=webpackmerge(baseConfig,{
  mode: 'development'
})
Copy the code

Base.config.js file code:

const path = require('path');
const webpack = require('webpack');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const HtmlWebpackplugin = require('html-webpack-plugin');
module.exports = {
  entry: './src/index.js'.output: {
    filename: 'built.js'.path: path.resolve(__dirname, '.. /build')},module: {
    rules: [{test: /\.vue$/,
        use: ['vue-loader']]}},resolve: {
    alias: {
      'vue$': 'vue/dist/vue.esm.js'}},plugins: [
    new VueLoaderPlugin(),
    new webpack.BannerPlugin(Copyright @ 2016 All Rights Reserved: Small Cattle online),
    new HtmlWebpackplugin({
      template:'./index.html'}})],Copy the code

Finally, we need to configure in package.json how to execute the configuration file when packaging, because webpack only recognizes the webpack.config.js configuration file by default.

 "build": "webpack --config ./config/prod.config.js"."dev":"npx webpack serve --config ./config/dev.config.js"
Copy the code

Dev-server starts differently from webpack5, as shown in the official website

Webpack.js.org/configurati…

Our configuration file is then successfully configured.

3. Summary

Although we used three files to configure webpack.config.js in only one file, which seems more troublesome, we actually need to configure a lot of content in development, and the separation of production and development is desirable and an optimized way to write. If you read the Vue-CLI scaffolding build project, you’ll see that the WebPack build section uses this approach