-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
vue.config.js
355 lines (326 loc) · 9.41 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
'use strict';
const path = require('path');
const { formatDate } = require('@liwb/cloud-utils');
const pkg = require('./package');
const webpack = require('webpack');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const chalk = require('chalk');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const Carefree = require('@liwb/carefree-webpack-plugin');
const {
host,
port,
source,
username,
password,
target,
} = require('./carefree');
const VueRouterInvokeWebpackPlugin = require('@liwb/vue-router-invoke-webpack-plugin');
const SizePlugin = require('size-plugin');
// const TerserPlugin = require('terser-webpack-plugin');
const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin');
const resolve = (dir) => {
return path.join(__dirname, './', dir);
};
const isProd = () => {
return process.env.NODE_ENV === 'production';
};
const isCarefree = () => {
return process.env.NODE_ENV === 'carefree';
};
function addStyleResource(rule) {
rule
.use('style-resource')
.loader('style-resources-loader')
.options({
patterns: [
path.resolve(__dirname, 'src/assets/less/variable.less'),
path.resolve(__dirname, 'node_modules/magicless/magicless.less'),
],
injector: 'prepend',
});
}
// cdn
const cdn = {
// 开发环境
dev: {
css: [],
js: [],
},
// 生产环境
build: {
css: [],
js: [
'https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.6/vue-router.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.1/vuex.min.js',
],
},
};
const externals = {
vue: 'Vue',
'vue-router': 'VueRouter',
axios: 'axios',
};
const genPlugins = () => {
const plugins = [
new ProgressBarPlugin({
format:
' build [:bar] ' +
chalk.green.bold(':percent') +
' (:elapsed seconds)',
clear: false,
}),
new VueRouterInvokeWebpackPlugin({
dir: 'src/views',
// must set the alias for the dir option which you have set
alias: '@/views',
mode: 'hash',
routerDir: 'src/router',
ignore: ['images', 'components'],
redirect: [
{
redirect: '/hello',
path: '/',
},
],
}),
// 为静态资源文件添加 hash,防止缓存
new AddAssetHtmlPlugin([
{
filepath: path.resolve(__dirname, './public/config.local.js'),
hash: true,
},
{
filepath: path.resolve(__dirname, './public/console.js'),
hash: true,
},
]),
// bannerPlugin
new webpack.BannerPlugin({
banner: `Current version ${pkg.version} and build time ${formatDate(
new Date(),
'yyyy-MM-dd HH:mm:ss'
)}`,
}),
new DuplicatePackageCheckerPlugin(),
];
if (isProd()) {
plugins.push(
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
threshold: 10240,
minRatio: 0.8,
cache: true,
}),
// 在每次执行打包命令后打印出本次构建的资源体积并和上次构建结果进行对比
new SizePlugin()
);
}
if (isCarefree()) {
plugins.push(
new Carefree({
qrcodeUrl: `http://www.example.com/${pkg.name}/index.html`,
devtool: 'true',
ssh: {
host,
port,
source,
username,
password,
target: `${target}${pkg.name}`,
},
})
);
}
return plugins;
};
// const getOptimization = () => {
// let optimization = {};
// if (isProd()) {
// optimization = {
// // https://webpack.docschina.org/configuration/optimization/#optimization-minimizer
// minimizer: [
// new TerserPlugin({
// terserOptions: {
// // https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions
// compress: {
// warnings: false,
// drop_console: true,
// drop_debugger: true,
// pure_funcs: ['console.log'],
// },
// },
// }),
// ],
// };
// }
// return optimization;
// };
module.exports = {
/**
* You can set by yourself according to actual condition
* You will need to set this if you plan to deploy your site under a sub path,
* for example GitHub pages. If you plan to deploy your site to https://foo.github.io/bar/,
* then assetsPublicPath should be set to "/bar/".
* In most cases please use '/' !!!
* Detail https://cli.vuejs.org/config/#publicPath
*/
publicPath: './',
assetsDir: isCarefree() ? './' : 'static',
lintOnSave: process.env.NODE_ENV !== 'production',
productionSourceMap: false,
// webpack-dev-server 相关配置
devServer: {
open: process.platform === 'darwin',
host: '0.0.0.0',
port: 3000,
https: false,
hotOnly: false,
overlay: {
warnings: false,
errors: true,
},
},
// css相关配置
css: {
// 是否使用css分离插件 ExtractTextPlugin
extract: isProd() ? true : false,
// 开启 CSS source maps?
sourceMap: isProd() ? true : false,
// css预设器配置项
loaderOptions: {},
},
configureWebpack: () => ({
name: `${pkg.name}`,
resolve: {
alias: {
'@': resolve('src'),
'@assets': resolve('src/assets'),
'@less': resolve('src/assets/less'),
'@js': resolve('src/assets/js'),
'@components': resolve('src/components'),
'@mixins': resolve('src/mixins'),
'@filters': resolve('src/filters'),
'@store': resolve('src/store'),
'@views': resolve('src/views'),
// 文件别名
services: resolve('src/services'),
variable: resolve('src/assets/less/variable.less'),
utils: resolve('node_modules/@liwb/cloud-utils/dist/cloud-utils.esm'),
mixins: resolve('node_modules/magicless/magicless.less'),
},
},
plugins: genPlugins(),
externals: isProd() ? externals : {},
// 生产环境去掉 console.log
// https://github.com/cklwblove/vue-cli3-template/issues/12
// optimization: getOptimization()
}),
// webpack配置
// see https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.md
chainWebpack: (config) => {
config.plugins.delete('preload'); // TODO: need test
config.plugins.delete('prefetch'); // TODO: need test
// module
// style-resources-loader
const types = ['vue-modules', 'vue', 'normal-modules', 'normal'];
types.forEach((type) =>
addStyleResource(config.module.rule('less').oneOf(type))
);
// svg
// exclude icons
config.module
.rule('svg')
.exclude.add(resolve('src/icons'))
.end();
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/icons'))
.end()
.use('url-loader')
.loader('url-loader')
.end();
config.when(process.env.NODE_ENV === 'development', (config) =>
config.devtool('cheap-eval-source-map')
);
// webpack-html-plugin
config.plugin('html').tap((args) => {
args[0].minify = {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
};
// 添加CDN参数到htmlWebpackPlugin配置中
if (process.env.NODE_ENV === 'production') {
args[0].cdn = cdn.build;
}
return args;
});
// set preserveWhitespace
config.module
.rule('vue')
.use('vue-loader')
.loader('vue-loader')
.tap((options) => {
options.compilerOptions.preserveWhitespace = true;
return options;
})
.end();
// optimization
// https://imweb.io/topic/5b66dd601402769b60847149
config.when(process.env.NODE_ENV === 'production', (config) => {
// vue-cli4
// https://cli.vuejs.org/migrating-from-v3/#vue-cli-service
// config.optimization.minimizer('terser').tap((args) => {
// args[0].terserOptions.compress.drop_console = true;
// return args;
// });
config
.plugin('ScriptExtHtmlWebpackPlugin')
.after('html')
.use('script-ext-html-webpack-plugin', [
{
// `runtime` must same as runtimeChunk name. default is `runtime`
inline: /runtime\..*\.js$/,
},
])
.end();
config.optimization.splitChunks({
chunks: 'all',
cacheGroups: {
vendors: {
name: 'chunk-vendors',
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: 'initial', // 只打包初始时依赖的第三方
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // 可自定义拓展你的规则
minChunks: 3, // 最小公用次数
priority: 5,
reuseExistingChunk: true,
},
},
});
config.optimization.runtimeChunk('single');
});
},
pluginOptions: {
lintStyleOnBuild: true,
stylelint: {},
},
};