webpack5以上抽离配置文件(生产开发分明)

1.为什么要分离配置文件

在我们开发过程中,经常在webpack.config.js文件中配置很多东西,不管是开发环境下,还是生产环境下。但是当我们在生产环境下打包时,其实很多我们开发环境下的配置时用不到的。那么当我们把所有的配置写在一个文件中时,那是不太稳妥的。

因此我们需要抽离配置文件。

2.实施

我们需要安装webpack-merge插件

 npm install webpack-merge --save-dev

接着分离文件,将配置文件分为三个文件,分别时base.config、pron.config、dev.config

其作用为

base.config:公共配置抽离部分

pron.config:生产环境相关配置

dev.config: 开发环境相关配置

接着我们可以使用merge进行配置文件的合并:

dev.config.js文件代码

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

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

prod.config.js文件代码

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

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

base.config.js文件代码:

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('版权所有所有:小牲口online'),
    new HtmlWebpackplugin({
    
    
      template:'./index.html'
    })
  ],
}

最后我们还需要在package.json中配置打包时如何执行配置文件,因为webpack默认是只识别webpack.config.js配置文件的。

 "build": "webpack --config ./config/prod.config.js",
 "dev":"npx webpack serve --config ./config/dev.config.js"

因为我这里使用的是webpack5以上的版本,因此dev-server的启动方式和webpack5以下的有所不同,详细可见官网

https://webpack.js.org/configuration/dev-server/#root 在这里插入图片描述

这时我们的配置文件就算是配置成功了。

3.总结

虽然我们使用了三个文件来进行配置,而webpack.config.js只用了一个文件来进行配置,仿佛更加麻烦了,实际上在开发中,我们需要配置大量的内容,生产和开发分离是可取的,也是一种优化的写法。如果你阅读过vue-cli脚手架构建的项目会发现其中webpack构建部分使用的就是此方法

猜你喜欢

转载自blog.csdn.net/M_Edison/article/details/115443317