1.在根目录下新建一个文件夹build,在该文件夹下建立三个文件:base.config.js(公共)、prod.config.js(生产)、dev.config.js(开发)
2.在各个文件下添加相关的代码,例如:
base.config.js:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require("path");
const webpack = require("webpack");
const uglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: "./src/main.js", //入口
output: { //出口
path: path.resolve(__dirname, "../dist"),
filename: "bundle.js"
},
module: {
rules: [{
test: /\.css$/,
// css-loader值负责将css文件进行加载
// style-loader负责将样式添加到DOM中
use: ['style-loader', 'css-loader'],
},
{
test: /\.vue$/,
use: ['vue-loader']
},
{
test: /\.(png|jpg|gif|jpeg)$/i,
use: [{
loader: 'url-loader',
options: {
limit: 8192,
name: "img/[name].[hash:8].[ext]"
},
}, ],
},
],
},
resolve: {
alias: {
"vue$": "vue/dist/vue.esm.js"
}
},
plugins: [
new webpack.BannerPlugin('最终版权归<WRM>所有'),
new HtmlWebpackPlugin({
template: "index.html"
}),
// new uglifyJsPlugin()
],
// devServer: {
// contentBase: './dist', //为哪一个文件夹提供本地服务,默认是根文件夹,这里填写./dist
// inline: true //页面实时刷新
// }
}
prod.config.js:
const uglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
plugins: [
new uglifyJsPlugin()
],
}
dev.config.js:
module.exports = {
devServer: {
contentBase: './dist', //为哪一个文件夹提供本地服务,默认是根文件夹,这里填写./dist
inline: true //页面实时刷新
}
}
3.将三个文件进行组合(合并)
(1)安装:
cnpm install webpack-merge@4.1.5 --save-dev
(2)prod.config.js修改代码为:
const uglifyJsPlugin = require('uglifyjs-webpack-plugin');
const webpackMerge = require('webpack-merge');
const baseConfig = require('./base.config');
module.exports = webpackMerge(baseConfig,{
plugins: [
new uglifyJsPlugin()
],
})
dev.config,js下修改代码为:
const webpackMerge = require('webpack-merge');
const baseConfig = require('./base.config');
module.exports = webpackMerge(baseConfig, {
devServer: {
contentBase: './dist', //为哪一个文件夹提供本地服务,默认是根文件夹,这里填写./dist
inline: true //页面实时刷新
}
})
这些步骤下来,之前的根目录下的webpack.config.js文件就可以删掉了
4.打开package.json文件,修改代码如下:
"build": "webpack --config ./build/prod.config.js",
"dev": "webpack-dev-server --open --config ./build/dev.config.js"
5.可以分别执行
npm run build
npm run dev
查看效果