Separate configuration files in webpack

Article Directory

In webpack.config.jssome configuration files is only useful during the development phase, the final package generated code, this configuration is not used, such as dev-server. But some configurations are not needed in the development stage, but are needed when packaging, such as the uglifyjs-webpack-plugin plug-in. If we write everything in this file without separation, it is obviously not good. Then we separate this configuration file.


step one

Create a build folder in the project root directory to store configuration files, and then create three js files, as shown in the figure:
Insert picture description here

  • The base.config.js file stores the basic configuration, the configuration needed in the development phase and the production phase
  • dev.config.js file, which stores the configuration used only in the development phase
  • The prod.config.js file, which stores the configuration only used in the production phase

Step two

Now you need to link the three configuration files together, use webpack-mergeand install:npm install webpack-merge --save-dev

My webpack version is 3.6.0 and webpack-merge version is 4.2.2

Next, use webpack-merge in the dev.config.js file and prod.config.js file

// prod.config.js
let UglifyWebpackPlugin = require('uglifyjs-webpack-plugin')
let webpackMerge = require('webpack-merge') //1.引入webpackMerge 
let baseConfig = require('./base.config')   //2.引入base.config.js

module.exports = webpackMerge(baseConfig,{
    
      //3.使用webpackMerge进行合并
  plugins:[
    new UglifyWebpackPlugin() //打包阶段才需要压缩js代码
  ]
})
//dev.config.js
let webpackMerge = require('webpack-merge');
let baseConfig = require('./base.config')

module.exports = webpackMerge(baseConfig,{
    
    
  devServer:{
    
     //这个配置只在开发阶段有用,打包生成最终代码的时候,这个配置就没有用了
    contentBase:'./dist',
    inline:true,
  }
})

Step three

Configure the command in scripts in the package.json file:

{
    
    
	 //...其它
	"scripts": {
    
    
	    "build": "webpack --config ./build/prod.config.js",
	    "dev": "webpack-dev-server --open --config ./build/dev.config.js"
	  }
}
  • In execution npm run buildtime, use prod.config.js profile
  • In execution npm run devtime, use dev.config.js profile

In addition, pay attention to the output configuration in base.config.js

module.exports = {
    
    
  entry: './src/main.js',
  output: {
    
    
   //注意这个地方是 ../dist,如果直接写 dist ,它会在build文件夹下生成dist文件夹
    path: path.join(__dirname, '../dist'),
    filename: 'bundle.js',
  }
}

data

The demo code download link of this blog: https://webchang.lanzous.com/iB6Irkh9lpc Password: f2wn

Guess you like

Origin blog.csdn.net/weixin_43974265/article/details/112723994