forked from staven630/vue-cli4-config
-
Notifications
You must be signed in to change notification settings - Fork 1
/
vue.config.js
282 lines (257 loc) · 8.27 KB
/
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
const SpritesmithPlugin = require("webpack-spritesmith");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
const webpack = require("webpack");
const path = require("path");
const fs = require("fs");
const resolve = dir => path.join(__dirname, dir);
const IS_PROD = ["production", "prod"].includes(process.env.NODE_ENV);
const glob = require('glob')
const pagesInfo = require('./pages.config')
const pages = {}
glob.sync('./src/**/main.js').forEach(p => {
let result = p.match(/\.\/src\/(.*)\/main\.js/)
result = result ? result[1] : '';
const key = result ? result : 'main';
if (pagesInfo[key]) {
pages[key] = {
entry: result ? `src/${result}/main.js` : 'src/main.js'
}
for (const info in pagesInfo[key]) {
pages[key] = {
...pages[key],
[info]: pagesInfo[key][info]
}
}
}
})
let has_sprite = true
let iconsObj;
let files;
try {
files = fs.readdirSync(resolve('./src/assets/icons'))
iconsObj = fs.readFileSync(resolve('./icons.json'), 'utf8')
iconsObj = JSON.parse(iconsObj)
has_sprite =
files && files.length
? files.some(item => {
let filename = item.toLocaleLowerCase().replace(/_/g, '-')
return !iconsObj[filename]
})
: false
} catch (error) {
const icons = {};
files.forEach(item => {
let filename = item.toLocaleLowerCase().replace(/_/g, '-')
icons[filename] = true
})
fs.writeFileSync(resolve('./icons.json'), JSON.stringify(icons, null, 2))
has_sprite = true
}
// 雪碧图样式处理模板
const SpritesmithTemplate = function (data) {
// pc
let icons = {}
let tpl = `.ico {
display: inline-block;
background-image: url(${data.sprites[0].image});
background-size: ${data.spritesheet.width}px ${data.spritesheet.height}px;
}`
data.sprites.forEach(sprite => {
const name = '' + sprite.name.toLocaleLowerCase().replace(/_/g, '-')
icons[`${name}.png`] = true
tpl = `${tpl}
.ico-${name}{
width: ${sprite.width}px;
height: ${sprite.height}px;
background-position: ${sprite.offset_x}px ${sprite.offset_y}px;
}
`
})
return tpl
}
module.exports = {
publicPath: IS_PROD ? process.env.VUE_APP_PUBLIC_PATH : "./", // 默认'/',部署应用包时的基本 URL
// outputDir: process.env.outputDir || 'dist', // 'dist', 生产环境构建文件的目录
// assetsDir: "", // 相对于outputDir的静态资源(js、css、img、fonts)目录
configureWebpack: config => {
const plugins = [];
if (has_sprite) {
// 生成雪碧图
plugins.push(
new SpritesmithPlugin({
src: {
cwd: path.resolve(__dirname, './src/assets/icons/'), // 图标根路径
glob: '**/*.png' // 匹配任意 png 图标
},
target: {
image: path.resolve(__dirname, './src/assets/images/sprites.png'), // 生成雪碧图目标路径与名称
// 设置生成CSS背景及其定位的文件或方式
css: [
[
path.resolve(__dirname, './src/assets/scss/sprites.scss'),
{
format: 'function_based_template'
}
]
]
},
customTemplates: {
function_based_template: SpritesmithTemplate
},
apiOptions: {
cssImageRef: '../images/sprites.png' // css文件中引用雪碧图的相对位置路径配置
},
spritesmithOptions: {
padding: 2
}
})
)
}
config.externals = {
vue: "Vue",
"element-ui": "ELEMENT",
"vue-router": "VueRouter",
vuex: "Vuex",
axios: "axios"
};
config.plugins = [...config.plugins, ...plugins];
},
chainWebpack: config => {
// 修复HMR
config.resolve.symlinks(true);
config
.plugin("ignore")
.use(
new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn$/)
);
// 添加别名
config.resolve.alias
.set("vue$", "vue/dist/vue.esm.js")
.set("@", resolve("src"))
.set("@apis", resolve("src/apis"))
.set("@assets", resolve("src/assets"))
.set("@scss", resolve("src/assets/scss"))
.set("@components", resolve("src/components"))
.set("@middlewares", resolve("src/middlewares"))
.set("@mixins", resolve("src/mixins"))
.set("@plugins", resolve("src/plugins"))
.set("@router", resolve("src/router"))
.set("@store", resolve("src/store"))
.set("@utils", resolve("src/utils"))
.set("@views", resolve("src/views"))
.set("@layouts", resolve("src/layouts"));
const cdn = {
// 访问https://unpkg.com/element-ui/lib/theme-chalk/index.css获取最新版本
css: ["//unpkg.com/[email protected]/lib/theme-chalk/index.css"],
js: [
"//unpkg.com/[email protected]/dist/vue.min.js", // 访问https://unpkg.com/vue/dist/vue.min.js获取最新版本
"//unpkg.com/[email protected]/dist/vue-router.min.js",
"//unpkg.com/[email protected]/dist/vuex.min.js",
"//unpkg.com/[email protected]/dist/axios.min.js",
"//unpkg.com/[email protected]/lib/index.js"
]
};
// 如果使用多页面打包,使用vue inspect --plugins查看html是否在结果数组中
// config.plugin("html").tap(args => {
// // html中添加cdn
// args[0].cdn = cdn;
// // 修复 Lazy loading routes Error
// args[0].chunksSortMode = "none";
// return args;
// });
// 防止多页面打包卡顿
config => config.plugins.delete('named-chunks')
// 多页面cdn添加
Object.keys(pagesInfo).forEach(page => {
config.plugin(`html-${page}`).tap(args => {
// html中添加cdn
args[0].cdn = cdn;
// 修复 Lazy loading routes Error
args[0].chunksSortMode = "none";
return args;
});
})
if (IS_PROD) {
// 压缩图片
config.module
.rule("images")
.test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
.use("image-webpack-loader")
.loader("image-webpack-loader")
.options({
mozjpeg: { progressive: true, quality: 65 },
optipng: { enabled: false },
pngquant: { quality: [0.65, 0.90], speed: 4 },
gifsicle: { interlaced: false },
webp: { quality: 75 }
});
// 打包分析
config.plugin("webpack-report").use(BundleAnalyzerPlugin, [
{
analyzerMode: "static"
}
]);
}
// 使用svg组件
const svgRule = config.module.rule("svg");
svgRule.uses.clear();
svgRule.exclude.add(/node_modules/);
svgRule
.test(/\.svg$/)
.use("svg-sprite-loader")
.loader("svg-sprite-loader")
.options({
symbolId: "icon-[name]"
});
const imagesRule = config.module.rule("images");
imagesRule.exclude.add(resolve("src/icons"));
config.module.rule("images").test(/\.(png|jpe?g|gif|svg)(\?.*)?$/);
return config;
},
pages,
css: {
extract: IS_PROD,
sourceMap: false,
loaderOptions: {
scss: {
// 向全局sass样式传入共享的全局变量, $src可以配置图片cdn前缀
// 详情: https://cli.vuejs.org/guide/css.html#passing-options-to-pre-processor-loaders
prependData: `
@import "@scss/variables.scss";
@import "@scss/mixins.scss";
@import "@scss/function.scss";
$src: "${process.env.VUE_APP_BASE_API}";
`
}
}
},
lintOnSave: false,
runtimeCompiler: true, // 是否使用包含运行时编译器的 Vue 构建版本
productionSourceMap: !IS_PROD, // 生产环境的 source map
parallel: require("os").cpus().length > 1,
pwa: {},
devServer: {
// overlay: { // 让浏览器 overlay 同时显示警告和错误
// warnings: true,
// errors: true
// },
// open: false, // 是否打开浏览器
// host: "localhost",
// port: "8080", // 代理断就
// https: false,
// hotOnly: false, // 热更新
proxy: {
"/api": {
target:
"https://www.easy-mock.com/mock/5bc75b55dc36971c160cad1b/sheets", // 目标代理接口地址
secure: false,
changeOrigin: true, // 开启代理,在本地创建一个虚拟服务端
// ws: true, // 是否启用websockets
pathRewrite: {
"^/api": "/"
}
}
}
}
};