为什么要区分打包呢?是因为如果开发环境的配置和生产环境的配置都放在一个文件里,那么配置的多,想要去切换这两种模式的打包,就显得很麻烦了,所以,建议把他们区分开来
1. 首先在项目根目录下创建三个文件存放到build文件夹
- webpack.common.js
存放两个模式下的公共配置
- webpack.dev.js
存放development模式下的配置
- webpack.prod.js
存放production模式下的配置
2.webpack.common.js的配置
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
entry: {
main: './src/main.js'
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader', 'postcss-loader']
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.vue$/,
use: ['vue-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({ template: 'src/index.html' }),
new CleanWebpackPlugin(),
new VueLoaderPlugin()
],
output: {
filename: '[name]_[hash:8].js',
path: path.resolve(__dirname, '../dist')
}
}
3.webpack.dev.js的配置
const webpack = require('webpack')
const merge = require('webpack-merge')
const commonConfig = require('./webpack.common')
const devConfig = {
mode: 'development',
devtool: 'cheap-module-eval-source-map',
devServer: {
open: true,
contentBase: './dist',
port: 8888,
hot: true, // 热加载
// hotOnly: true, // 即使html不生效,我也不让它刷新页面
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
optimization:{
usedExports:true
},
}
module.exports = merge(commonConfig,devConfig)
4.webpack.prod.js 的配置
const merge = require('webpack-merge')
const commonConfig = require('./webpack.common')
const prodConfig = {
mode: 'production',
devtool: 'cheap-module-source-map',
}
module.exports = merge(commonConfig,prodConfig)
5. 在package.json里进行配置
至此,简单地区分打包就完成了,这样我们去配置生产环境还是开发环境的配置,就很方便了