辰風依恛
文章35
标签0
分类11
关于vue.config.js

关于vue.config.js

关于vue.config.js

vue.config.js中常用的配置

在配置中绝大多数都是(可选项)

导出模块

常规操作还是用到了commjs语法

1
2
3
module.exports = {

}

publicPath 部署应用包的基本Url

部署应用包的基本Url,默认/, 可以设置为相对路径./,这样打出来的包,可以部署到任意路径上

1
2
3
4
5
let developmentPath='./';//开发环境-npm run serve时引用文件路径
let productionPath='./';//生产环境-npm run build打包后引用文件路径
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? productionPath: developmentPath, // 基本路径-引用文件的路
}

outputDir 输出文件目录

输出文件目录(打包后生成的目录,默认dist)

1
2
3
4
module.exports = {
outputDir: __dirname + '/server/dist', //build之后静态文件输出路径
//outputDir: 'dist',
}

assetsDir 打包后生成的静态资源目录

打包后生成的静态资源目录,默认“ ” ,也就是我们打包后的css,js等存放的位置

1
2
3
module.exports = {
assetsDir: 'static',
}

lintOnSave

是否在保存的时候检查

1
2
3
module.exports = {
lintOnSave: process.env.NODE_ENV !== 'production',// eslint-loader
}

productionSourceMap 生产环境的 source map

生产环境的 source map,可以将其设置为 false 以加速生产环境构建,默认值是true

1
2
3
module.exports = {
productionSourceMap: false,
}

devServer

可通过 devServer.proxy解决前后端跨域问题(反向代理)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
module.exports = {
// 反向代理
devServer: {
index: '/login.html', //默认打开文件
open: true, //自动打开浏览器
host: 'localhost', //默认打开域名
port: 8080, //默认打开端口号
https: false, //开启关闭https请求
hotOnly: false, //热更

proxy: {
// 配置跨域
'/api': {
target: 'http://dev.aabb.cn:8082/', //代理地址,这里设置的地址会代替axios中设置的baseURL
ws: true, //// proxy websockets
changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
pathRewrite: { //pathRewrite方法重写url
'^/api': '/',
},
},
},
},
}

扩展: hot 和 hotOnly 的区别是在某些模块不支持热更新的情况下,前者会自动刷新页面,后者不会刷新页面,而是在控制台输出热更新失败

打包时去除打印信息

上面已经提到过去掉打印的操作(console、debug)这里详细讲解一下

首先下载相关插件 uglifyjs-webpack-plugin

npm i -D uglifyjs-webpack-plugin

在vue.config.js文件中引入,并在configureWebpack的optimization中添加如下代码

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
const UglifyPlugin = require('uglifyjs-webpack-plugin')
module.exports = {

configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
// 为生产环境修改配置...
config.mode = 'production'
// 将每个依赖包打包成单独的js文件
let optimization = {

/*以下代码适用于uglifyjs-webpack-plugin 2.1.1及以前的版本*/
minimizer: [new UglifyPlugin({
uglifyOptions: {
compress: {
warnings: false,
drop_console: true, // console
drop_debugger: false,
pure_funcs: ['console.log'] // 移除console
}
}
})]

}
Object.assign(config, {
optimization
})
}

}
}

新版uglifyjs-webpack-plugin需写成以下方式

1
2
3
4
5
6
7
8
9
10
minimizer: [new UglifyPlugin({
uglifyOptions: {
warnings: false,
compress: {
drop_console: false, // console
drop_debugger: false,
pure_funcs: ['console.log'] // 移除console
}
}
})]

移动端.px2rem 响应样式

安装

npm i -S lib-flexible postcss-px2rem

引入 lib-flexible

在项目入口中main.js 中引入lib-flexible

1
2
3
import 'lib-flexible' 

# 注意事项: 由于flexible会动态给页面header中添加<meta name='viewport' >标签,所以务必请把目录 public/index.html 中的这个标签删除!!

配置postcss-px2rem

项目中vue.config.js中进行如下的配置

1
2
3
4
5
6
7
8
9
10
11
module.exports = { 
css: {
loaderOptions: {
css: {},
postcss: {
plugins: [ require('postcss-px2rem')({ remUnit: 37.5 })
]
}
}
}
}

设置页面动态标题

下载 vue-wechat-title

npm i -S vue-wechat-title

main.js中全局引入

1
2
import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)

App.vue中设置

1
2
3
4
5
6
<template>
<!-- 动态设置title -->
<div id="app" v-wechat-title='$route.meta.title'>
<router-view/>
</div>
</template>

开启gzip压缩

gzip压缩是一种http请求优化方式,通过减少文件体积来提高加载速度。html、js、css文件甚至json数据都可以用它压缩,可以减小60%以上的体积。webpack在打包时可以借助 compression webpack plugin 实现gzip压缩。

下载 compression webpack plugin

npm i -D compression-webpack-plugin

vue.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
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = {

configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
// 为生产环境修改配置...
config.mode = 'production';

if(openGzip){
config.plugins = [
...config.plugins,
new CompressionPlugin({
test:/\.js$|\.html$|.\css/, //匹配文件名
threshold: 10240,//对超过10k的数据压缩
deleteOriginalAssets: false //不删除源文件
})
]
}

} else {
// 为开发环境修改配置...
config.mode = 'development';
}

}
}

package.js 配置

1
2
3
4
5
6
{
"name": "demo-cli3",
"version": "1.0.0",
"openGizp": false,
...
}

优化打包chunk-vendors.js

当运行项目并且打包的时候,会发现chunk-vendors.js这个文件非常大,那是因为webpack将所有的依赖全都压缩到了这个文件里面,这时我们可以将其拆分,将所有的依赖都打包成单独的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
/*
利用splitChunks将每个依赖包单独打包,在生产环境下配置,代码如下
*/

configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
// 为生产环境修改配置...
config.mode = 'production'
// 将每个依赖包打包成单独的js文件
let optimization = {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 20000, // 依赖包超过20000bit将被单独打包
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name (module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
// npm package names are URL-safe, but some servers don't like @ symbols
return `npm.${packageName.replace('@', '')}`
}
}
}
}
}
Object.assign(config, {
optimization
})
}
}

vue.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// 打包多入口文件基本配置
let developmentPath = './';//开发环境-npm run serve时引用文件路径
let productionPath = './';//生产环境-npm run build打包后引用文件路径

const UglifyJsPlugin = require('uglifyjs-webpack-plugin')//生产环境取消打印
const CompressionWebpackPlugin = require('compression-webpack-plugin')//gzip压缩

const productionGzipExtensions = ['js', 'css']
const Version = 'V6.1'
const Timestamp = new Date().getTime()
function getPagesInfo() {
let pages = {}
const glob = require('glob') // 引入glob模块,用于扫描全部src/pages/**/main.js(返回的是一个数组)
glob.sync('src/pages/**/main.js').forEach((entry, i) => {
let name = entry.slice(10, -8)
pages[name] = {
entry: entry,
template: 'public.index.html',
filename: name + '.html',
title: '',
chunks: ["chunk-vendors", "chunk-common", name]
}
})
return pages
}
// 打包相关
module.exports = {
pages: getPagesInfo(),//多页面应用配置
publicPath: process.env.NODE_ENV === 'production' ? productionPath : developmentPath, // 基本路径-引用文件的路 __dirname + '/server/dist', //build之后静态文件输出路径
assetsDir: 'static',//静态资源大包位置
outputDir: __dirname + '/server/dist', //build之后静态文件输出路径
lintOnSave: process.env.NODE_ENV !== 'production',// 打包的时候eslint-loader检查
productionSourceMap: false,//source map 检查
// 启动服务器
devServer: {
index: '/login.html', //默认打开文件
open: true, //自动打开浏览器
host: 'localhost', //默认打开域名
port: 8080, //默认打开端口号
https: false, //开启关闭https请求
hotOnly: false, //热更
// 反向代理
proxy: {
// 配置跨域
'/api': {
target: 'http://dev.aabb.cn:8082/', //代理地址,这里设置的地址会代替axios中设置的baseURL
ws: true, //// proxy websockets
changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
pathRewrite: { //pathRewrite方法重写url
'^/api': '/',
},
},
},
},
// webpack配置 链式
chainWebpack: (config) => {
// 1、取消预加载增加加载速度
config.plugins.delete('preload')
config.plugins.delete('prefetch')

// 2、vue中使用SVG图标,并且想批量导入,然后需要使用的时候直接添加就可以
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]',
})
.end()

// 3、图片处理
const imagesRule = config.module.rule('images')
imagesRule.uses.clear() //清除原本的images loader配置
imagesRule
.test(/\.(jpg|gif|png|svg)$/)
.exclude.add(path.join(__dirname, '../node_modules')) //不对node_modules里的图片转base64
.end()
.use('url-loader')
.loader('url-loader')
.options({ name: 'img/[name].[hash:8].[ext]', limit: 6000000 })

config.optimization.splitChunks({
cacheGroups: {

vendors: {
name: 'chunk-vendors',
minChunks: pageNum,
test: /node_modules/,
priority: -10,
chunks: 'initial',
},

elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/, // in order to adapt to cnpm
},

commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true,
},
},
})
},
// webpack配置
configureWebpack: (config) => {
// 为生产环境修改配置
if (process.env.NODE_ENV === 'production') {

config.plugins.push(
// 1、取消打印
new UglifyJsPlugin({
uglifyOptions: {
compress: {
drop_debugger: true,//生产环境自动删除debugger
drop_console: true, //生产环境自动删除console
},
warnings: false,
},
sourceMap: false, //关掉sourcemap 会生成对于调试的完整的.map文件,但同时也会减慢打包速度
parallel: true, //使用多进程并行运行来提高构建速度。默认并发运行数:os.cpus().length - 1。
}),

// 2、gzip压缩
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 10240,
minRatio: 0.8,
})
)
}

// 在这里配置后,减少了压缩的包内容,需要在public/index.html通过cdn方式再引入,注意对应的版本
config.externals = {
vue: 'Vue',
'vue-router': 'VueRouter',
vuex: 'Vuex',
axios: 'axios',
jquery: '$',
moment: 'moment',
'mint-ui': 'MINT'
},


// 别名配置
Object.assign(config, {
// 开发生产共同配置
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@c': path.resolve(__dirname, './src/components'),
'@p': path.resolve(__dirname, './src/pages')
}
}
}),

config.output.filename = `[name].${Version}.${Timestamp}.js` //打包生成的文件
config.output.chunkFilename = `[name].${Version}.${Timestamp}.js`
},
// css相关
css: {
loaderOptions: {
// 配置全局sass
scss: {
additionalData: `@import "@/assets/css/reset.scss";@import "@/assets/css/globle.scss";` //注意配置的键名
},
// lib-flexible
postcss: {
plugins: [
//remUnit这个配置项的数值是多少呢??? 通常我们是根据设计图来定这个值,原因很简单,便于开发。
//假如设计图给的宽度是750,我们通常就会把remUnit设置为75,这样我们写样式时,可以直接按照设计图标注的宽高来1:1还原开发。
require('postcss-px2rem')({
remUnit: 37.5
})
]
}
}
},
parallel: require('os').cpus().length > 1, // 是否为 Babel 或 TypeScript 使用 thread-loader。该选项在系统的 CPU 有多于一个内核时自动启用,仅作用于生产构建。
pwa: {}, // PWA 插件相关配置
pluginOptions: {}, // 第三方插件配置
};
本文作者:辰風依恛
本文链接:https://766187397.github.io/2025/07/10/%E5%85%B3%E4%BA%8Evue.config.js/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可
×