-
Notifications
You must be signed in to change notification settings - Fork 0
/
vue.config.js
404 lines (390 loc) · 12.8 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
const path = require("path");
const webpack = require("webpack");
const glob = require("glob-all");
const PurgecssPlugin = require("purgecss-webpack-plugin");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
// const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
// const CompressionWebpackPlugin = require("compression-webpack-plugin");
const PrerenderSpaPlugin = require("prerender-spa-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin');
// const AliOssPlugin = require("webpack-oss");
const resolve = dir => path.join(__dirname, dir);
console.log('当前环境', process.env.NODE_ENV)
const IS_PROD = ["production", "prod", "test", "dev", "qa","uat"].includes(process.env.NODE_ENV);
// const SpritesmithPlugin = require('webpack-spritesmith')
// let has_sprite = true
// const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i;
// const addStylusResource = rule => {
// rule
// .use("style-resouce")
// .loader("style-resources-loader")
// .options({
// patterns: [resolve("src/assets/stylus/variable.styl")]
// });
// };
// try {
// let result = fs.readFileSync(path.resolve(__dirname, './icons.json'), 'utf8')
// result = JSON.parse(result)
// const files = fs.readdirSync(path.resolve(__dirname, './src/assets/icons'))
// has_sprite = files && files.length ? files.some(item => {
// let filename = item.toLocaleLowerCase().replace(/_/g, '-')
// return !result[filename]
// }) : false
// } finally {
// has_sprite = false
// }
// 雪碧图样式处理模板
// 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;
// }
// `
// })
// fs.writeFile(
// path.resolve(__dirname, './icons.json'),
// JSON.stringify(icons, null, 2),
// (err, data) => {}
// )
// return tpl
// }
// const format = AliOssPlugin.getFormat();
console.log('是什么', IS_PROD, process.env.NODE_ENV, process.env.VUE_APP_BASE_API_LEAGUE)
module.exports = {
publicPath: IS_PROD ? process.env.VUE_APP_PUBLIC_PATH : "./", // 默认'/',部署应用包时的基本 URL
// outputDir: IS_PROD ? "/official/" : "", // 'dist', 生产环境构建文件的目录
// assetsDir: "", // 相对于outputDir的静态资源(js、css、img、fonts)目录
configureWebpack: config => {
const plugins = [];
plugins.push(
new CopyWebpackPlugin([
{
from: './static',
// to: 'static',
ignore: ['.*']
}
])
)
if (IS_PROD) {
// 去除多余css
/*plugins.push(
new PurgecssPlugin({
paths: glob.sync([resolve("./!**!/!*.vue")]),
extractors: [
{
extractor: class Extractor {
static extract(content) {
const validSection = content.replace(
/<style([\s\S]*?)<\/style>+/gim,
""
);
return validSection.match(/[A-Za-z0-9-_:/]+/g) || [];
}
},
extensions: ["html", "vue"]
}
],
whitelist: ["html", "body"],
whitelistPatterns: [/el-.*!/],
whitelistPatternsChildren: [/^token/, /^pre/, /^code/]
})
);*/
// plugins.push(
// new UglifyJsPlugin({
// uglifyOptions: {
// compress: {
// warnings: false,
// drop_console: true,
// drop_debugger: false,
// pure_funcs: ["console.log"] //移除console
// }
// },
// sourceMap: false,
// parallel: true
// })
// );
// 利用splitChunks单独打包第三方模块
config.optimization = {
splitChunks: {
cacheGroups: {
libs: {
name: "chunk-libs",
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: "initial"
},
elementUI: {
name: "chunk-elementUI",
priority: 20,
test: /[\\/]node_modules[\\/]element-ui[\\/]/,
chunks: "all"
}
}
}
};
// gzip
// plugins.push(
// new CompressionWebpackPlugin({
// filename: "[path].gz[query]",
// algorithm: "gzip",
// test: productionGzipExtensions,
// threshold: 10240,
// minRatio: 0.8
// })
// );
plugins.push(
new webpack.ProvidePlugin({
$:"jquery",
jQuery:"jquery",
"windows.jQuery":"jquery"
})
);
// 预加载
plugins.push(
new PrerenderSpaPlugin({
staticDir: resolve("dist"),
routes: [
"/", "/login", "/register", "/componyInfo", "/ridicule",
"/about", "/mine", "/myLiuyan", "/myRidicule",
"/mine", "/addCompany", "/addRidicule",
"/noteBook"
],
postProcess(ctx) {
console.log('是什么东西呀', ctx)
ctx.route = ctx.originalRoute;
ctx.html = ctx.html.split(/>[\s]+</gim).join("><");
if (ctx.route.endsWith(".html")) {
ctx.outputPath = path.join(__dirname, "dist", ctx.route);
}
return ctx;
},
minify: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
decodeEntities: true,
keepClosingSlash: true,
sortAttributes: true
},
renderer: new PrerenderSpaPlugin.PuppeteerRenderer({
// 需要注入一个值,这样就可以检测页面当前是否是预渲染的
inject: {},
headless: true,
renderAfterTime: 5000,
// 视图组件是在API请求获取所有必要数据后呈现的,因此我们在dom中存在“data view”属性后创建页面快照
renderAfterDocumentEvent: "render-event"
})
})
);
// plugins.push(
// new AliOssPlugin({
// accessKeyId: process.env.ACCESS_KEY_ID,
// accessKeySecret: process.env.ACCESS_KEY_SECRET,
// region: process.env.REGION,
// bucket: process.env.BUCKET,
// prefix: process.env.PREFIX,
// exclude: /.*\.html$/,
// format
// })
// );
}
// config.externals = {
// vue: "Vue",
// "element-ui": "ELEMENT",
// "vue-router": "VueRouter",
// vuex: "Vuex",
// axios: "axios"
// };
// 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.plugins = [...config.plugins, ...plugins];
},
chainWebpack: config => {
// 修复HMR
config.resolve.symlinks(true);
config
.plugin("ignore")
.use(
new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn$/)
);
// const cdn = {
// // 访问https://unpkg.com/element-ui/lib/theme-chalk/index.css获取最新版本
// css: ["//unpkg.com/element-ui@2.10.1/lib/theme-chalk/index.css"],
// js: [
// "//unpkg.com/vue@2.6.10/dist/vue.min.js", // 访问https://unpkg.com/vue/dist/vue.min.js获取最新版本
// "//unpkg.com/vue-router@3.0.6/dist/vue-router.min.js",
// "//unpkg.com/vuex@3.1.1/dist/vuex.min.js",
// "//unpkg.com/axios@0.19.0/dist/axios.min.js",
// "//unpkg.com/element-ui@2.10.1/lib/index.js"
// ]
// };
config.plugin("html").tap(args => {
// 修复 Lazy loading routes Error
args[0].chunksSortMode = "none";
// html中添加cdn
// args[0].cdn = cdn;
return args;
});
// 添加别名
config.resolve.alias
.set("vue$", "vue/dist/vue.esm.js")
.set("@", resolve("src"))
.set("@assets", resolve("src/assets"))
.set("@scss", resolve("src/assets/scss"))
.set("@components", resolve("src/components"))
.set("@plugins", resolve("src/plugins"))
.set("@views", resolve("src/views"))
.set("@router", resolve("src/router"))
.set("@store", resolve("src/store"))
.set("@layouts", resolve("src/layouts"))
.set("@static", resolve("src/static"));
// 压缩图片
// config.module
// .rule("images")
// .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 }
// });
// 全局添加scss mixins 混入配置
const types = ["vue-modules", "vue", "normal-modules", "normal"];
types.forEach(type => {
//匹配到所有需要导入的文件
config.module
.rule("scss")
.oneOf(type)
.use("style-resource")
.loader("style-resources-loader")
.options({
patterns: [
path.resolve(
__dirname,
"src/assets/scss/mixins.scss"
) /*,
path.resolve(__dirname, "src/assets/scss/utils.scss")*/
]
});
});
// 打包分析
if (process.env.IS_ANALYZ) {
config.plugin("webpack-report").use(BundleAnalyzerPlugin, [
{
analyzerMode: "static"
}
]);
}
if (IS_PROD) {
// config.optimization.delete("splitChunks");
}
return config;
},
// css: {
// module: false,
// extract: IS_PROD,
// sourceMap: false,
// loaderOptions: {
// scss: {
// // 向全局sass样式传入共享的全局变量, $src可以配置图片cdn前缀
// data: `
// @import "@scss/config.scss";
// @import "@scss/variables.scss";
// @import "@scss/mixins.scss";
// @import "@scss/utils.scss";
// $src: "${process.env.VUE_APP_OSS_SRC}";
// `
// }
// }
// },
transpileDependencies: [],
lintOnSave: false,
runtimeCompiler: true, // 是否使用包含运行时编译器的 Vue 构建版本
productionSourceMap: !IS_PROD, // 生产环境的 source map
parallel: false, //false,// require("os").cpus().length > 1,
pwa: {
themeColor: 'none',
iconPaths: {
favicon32: 'favicon.ico',
favicon16: 'favicon.ico',
appleTouchIcon: 'favicon.ico',
maskIcon: 'favicon.ico',
msTileImage: 'favicon.ico'
}
},
devServer: {
// overlay: { // 让浏览器 overlay 同时显示警告和错误
// warnings: true,
// errors: true
// },
open: true, // 是否打开浏览器
host: "localhost",
port: "8080", // 代理断就
https: false,
hotOnly: false, // 热更新
proxy: {
"/api": {
target: 'https://monkeysmall.com/api/', // homePage Banner
// target: "http://localhost:8080/api/",
secure: false,
changeOrigin: true, // 开启代理,在本地创建一个虚拟服务端
// ws: true, // 是否启用websockets
pathRewrite: {
"^/api": ""
}
},
// "/leagueApi": {
// target: process.env.VUE_APP_BASE_API_LEAGUE, // homePage Banner
// secure: false,
// changeOrigin: true, // 开启代理,在本地创建一个虚拟服务端
// // ws: true, // 是否启用websockets
// pathRewrite: {
// "^/leagueApi": ""
// }
// },
}
}
};