Vue CLi3 修改webpack配置
# Vue CLi3 修改 webpack 配置
# 审查项目的 webpack 配置
因为 @vue/cli-service
对 webpack 配置进行了抽象,当你想查看 webpack 的配置时可以使用 inspect
命令:
vue inspect # 在终端打印 webpack配置信息
1
vue inspect > output.js # 把webpack配置信息生成到output.js文件
1
注意,output.js
文件不是一个有效的 webpack 配置文件,仅用于审查。
# 修改 webpack 配置
以修改路径别名为例:
项目根目录创建文件
vue.config.js
参考如下代码修改路径别名:
// vue.config.js
const path = require("path");
const resolve = (dir) => path.resolve(__dirname, dir);
module.exports = {
chainWebpack: (config) => {
config.resolve.alias.set("styles", resolve("src/assets/styles"));
},
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 参考
const path = require("path");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const ProxyAgent = require("proxy-agent");
const resolve = (dir) => path.resolve(__dirname, dir);
module.exports = {
outputDir: process.env.outputDir || "dist", // 'dist', 生产环境构建文件的目录
runtimeCompiler: true,
assetsDir: "static",
productionSourceMap: false, // 生产环境的 source map
parallel: require("os").cpus().length > 1,
configureWebpack: (config) => {
// 公共配置
// cdn引用时配置externals 防止将某些 import 的包(package)打包到 bundle 中,而是在运行时(runtime)再去从外部获取这些扩展依赖
config.externals = {
vue: "Vue",
"vue-router": "VueRouter",
"element-ui": "ELEMENT",
vuex: "Vuex",
axios: "axios",
};
config.resolve.alias = Object.assign({}, config.resolve.alias, {
src: resolve("src/common"),
common: resolve("src/views/common"),
static: resolve("static"),
});
if (process.env.NODE_ENV === "production") {
// 为生产环境修改配置...
config.optimization = {
minimizer: [
new UglifyJsPlugin({
uglifyOptions: {
compress: {
drop_console: true, // console
drop_debugger: false,
pure_funcs: ["console.log"], // 移除console
},
},
}),
],
};
} else {
// 为开发环境修改配置...
}
},
css: {
loaderOptions: {
css: {
importLoaders: 1, // @import 引入的文件可被一个loader处理 (2 可被两个loader处理)
},
},
},
devServer: {
port: 80,
disableHostCheck: true, // 可使用本地host配置的域名访问
proxy: {
"/api": {
agent: new ProxyAgent("http://132.128.11.12"),
target: "http://132.128.11.12",
ws: false,
changeOrigin: true,
},
},
},
};
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
53
54
55
56
57
58
59
60
61
62
63
64
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
53
54
55
56
57
58
59
60
61
62
63
64
上次更新: 2020/12/28, 20:12:00