0%

webpack-配置文件的分离

1.在根目录下新建一个文件夹build,在该文件夹下建立三个文件:base.config.js(公共)、prod.config.js(生产)、dev.config.js(开发)
2.在各个文件下添加相关的代码,例如:
base.config.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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:

1
2
3
4
5
6
const uglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
plugins: [
new uglifyJsPlugin()
],
}

dev.config.js:

1
2
3
4
5
6
7
module.exports = {
devServer: {
contentBase: './dist', //为哪一个文件夹提供本地服务,默认是根文件夹,这里填写./dist
inline: true //页面实时刷新

}
}

3.将三个文件进行组合(合并)
(1)安装:

1
cnpm install webpack-merge@4.1.5 --save-dev

(2)prod.config.js修改代码为:

1
2
3
4
5
6
7
8
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下修改代码为:

1
2
3
4
5
6
7
8
9
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文件,修改代码如下:

1
2
"build": "webpack --config ./build/prod.config.js",
"dev": "webpack-dev-server --open --config ./build/dev.config.js"

在这里插入图片描述
5.可以分别执行

1
npm run build
1
npm run dev

查看效果