-
Notifications
You must be signed in to change notification settings - Fork 2
/
webpack.config.js
385 lines (366 loc) · 11 KB
/
webpack.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
/**
* This file is part of vue-boilerplate.
* @link : https://zhaiyiming.com/
* @author : Emil Zhai ([email protected])
* @modifier : Emil Zhai ([email protected])
* @copyright: Copyright (c) 2018 TINYMINS.
*/
/**
* Set environments (fallback to build)
*/
require('./webpack/env').fallback(['build']);
/**
* Require must after set environments
*/
const chalk = require('chalk');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const CssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const moment = require('moment');
const MomentLocalesWebpackPlugin = require('moment-locales-webpack-plugin');
const path = require('path');
const openBrowser = require('react-dev-utils/openBrowser');
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const TerserWebpackPlugin = require('terser-webpack-plugin');
const webpack = require('webpack');
const WebpackAssetsManifest = require('webpack-assets-manifest');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const merge = require('webpack-merge').merge;
const WebpackBar = require('webpackbar');
const GenerateSW = require('workbox-webpack-plugin').GenerateSW;
const VueLoaderPlugin = require('vue-loader').VueLoaderPlugin;
const loaders = require('./webpack/loaders');
const plugins = require('./webpack/plugins');
const utils = require('./webpack/utils');
const packageConfig = require('./package.json');
const PUBLIC_PATHNAME = process.env.PUBLIC_PATH.replace(/https?:\/\/[^/]+/u, '');
const currentTime = Date.now();
const BUILD_TIMESTAMP = String(currentTime);
const BUILD_TIME_STRING = moment(currentTime).format('YYYY/MM/DD HH:mm:ss');
// https://webpack.js.org/configuration/stats/
const stats = utils.isProd
? {
colors: true,
entrypoints: false,
modules: false,
children: false,
}
: 'minimal';
let skipInstruction = false;
/** @type {webpack.Configuration[]} */
const webpackConfigs = [{
entry: {
app: utils.fullPath('src/entry/client.ts'),
},
output: {
path: process.env.DIST_PATH,
filename: 'js/[name].[chunkhash:4].js',
chunkFilename: 'js/[name].[chunkhash:4].js',
publicPath: process.env.PUBLIC_PATH,
},
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.tx', '.json', '.vue'],
alias: {
vue$: 'vue/dist/vue.esm.js',
'@': utils.fullPath('src'),
':': utils.fullPath('static'),
},
modules: [
utils.fullPath('src'),
'node_modules',
],
fallback: {
path: require.resolve('path-browserify'),
util: require.resolve('util/'),
},
},
module: {
rules: [
...loaders.scriptLoaders(),
...loaders.styleLoaders({ extract: true }),
...loaders.assetsLoaders(),
],
},
cache: {
type: 'filesystem',
buildDependencies: {
// It's recommended to set cache.buildDependencies.config: [__filename] in your webpack configuration to get the latest configuration and all dependencies.
// https://webpack.js.org/configuration/cache/#cachebuilddependencies
config: [__filename],
},
},
plugins: [
// util requires this internally
new webpack.ProvidePlugin({ process: 'process/browser' }),
// To strip all locales except “en” and “zh-cn”
// (“en” is built into Moment and can’t be removed)
new MomentLocalesWebpackPlugin({
localesToKeep: ['zh-cn'],
}),
// new CaseSensitivePathsPlugin(),
new WebpackBar({
name: `${utils.isProd ? 'Production' : 'Development'}: ${process.env.BUILD_TARGET}`,
color: utils.isProd ? '#569fff' : '#0dbc79',
}),
// new webpack.ProgressPlugin({ percentBy: 'entries' }),
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new VueLoaderPlugin(),
new webpack.EnvironmentPlugin({
NODE_ENV: process.env.NODE_ENV,
NODE_ACTION: process.env.NODE_ACTION,
ROUTER_MODE: process.env.ROUTER_MODE,
PUBLIC_PATH: process.env.PUBLIC_PATH,
BUILD_TIMESTAMP,
BUILD_TIME_STRING,
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: './index.html',
template: utils.fullPath('index.html'),
inject: 'body',
title: packageConfig.title,
// favicon: utils.fullPath('src/assets/favicon.ico'),
publicPath: process.env.PUBLIC_PATH,
}),
// Webpack plugin that runs TypeScript type checker on a separate process.
new ForkTsCheckerWebpackPlugin(),
],
}];
if (utils.isProd) {
webpackConfigs.push({
mode: 'production',
optimization: {
runtimeChunk: {
name: 'runtime', // webpack runtime
},
chunkIds: 'named',
moduleIds: 'deterministic',
splitChunks: {
chunks: 'all',
minSize: 20000,
minRemainingSize: 0,
minChunks: 2,
maxAsyncRequests: 30,
maxInitialRequests: 30,
enforceSizeThreshold: 50000,
automaticNameDelimiter: '.',
cacheGroups: {
vue: {
filename: 'js/vue-family-bundle.js',
name: 'vue-family-bundle',
test: /[/\\]node_modules[/\\](vue|vue-router|vuex|vuex-router-sync)[/\\]/u,
chunks: 'initial',
},
route: {
filename: 'js/route.[hash:24].js',
name: 'route',
test: /[/\\]src[/\\](router)[/\\]/u,
chunks: 'initial',
},
store: {
filename: 'js/store.[hash:24].js',
name: 'store',
test: /[/\\]src[/\\](store)[/\\]/u,
chunks: 'initial',
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true,
},
},
},
minimizer: [
new CssMinimizerWebpackPlugin({
minify: CssMinimizerWebpackPlugin.cssnanoMinify,
minimizerOptions: {
preset: ['default', { discardComments: { removeAll: true } }],
},
}),
new TerserWebpackPlugin({
parallel: true,
terserOptions: {
compress: {
// collapse_vars: false, // Bug: https://github.com/terser-js/terser/issues/369
// drop_console: true,
// pure_funcs: ['console.log'],
},
mangle: true, // Note `mangle.properties` is `false` by default.
},
}),
],
},
performance: {
hints: 'warning',
maxAssetSize: 3000000,
maxEntrypointSize: 2000000,
},
stats,
});
} else {
webpackConfigs.push({
mode: 'development',
stats,
devtool: 'inline-source-map',
});
}
if (utils.isRun) {
webpackConfigs.push({
// https://webpack.js.org/configuration/dev-server/
devServer: {
static: {
directory: path.join(__dirname, './static'),
publicPath: `${PUBLIC_PATHNAME}static`,
},
client: {
overlay: {
warnings: false,
errors: true,
},
},
historyApiFallback: {
disableDotRule: true,
rewrites: [
{ from: /./u, to: path.posix.normalize(path.posix.join(PUBLIC_PATHNAME, '/index.html')) },
],
},
hot: true,
compress: true,
host: '0.0.0.0',
port: process.env.PORT,
allowedHosts: 'all',
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
proxy: {
'/api': {
target: 'https://dev.haimanchajian.com',
pathRewrite: {
'^/api': '/api',
},
changeOrigin: true,
},
},
devMiddleware: {
publicPath: PUBLIC_PATHNAME,
stats,
},
onListening: (server) => {
const { port } = server.server.address();
server.compiler.hooks.done.tap('done', () => {
if (skipInstruction) {
return;
}
setImmediate(() => {
console.log();
console.log(chalk.green.bold('Running at ') + chalk.cyan.bold(`http://localhost:${port}${PUBLIC_PATHNAME}`) + ' '.repeat(10) + chalk.magenta.bold(`[${packageConfig.name}]`));
console.log();
openBrowser(`http://localhost:${port}${PUBLIC_PATHNAME}`);
skipInstruction = true;
});
});
},
},
});
} else {
webpackConfigs.push({
plugins: [
new CopyWebpackPlugin({
patterns: [
{
from: './static',
to: './static',
filter: pathname => !pathname.endsWith('/.gitkeep'),
noErrorOnMissing: true,
},
],
}),
new WebpackAssetsManifest({
transform: (assets, manifest) => ({
publicPath: process.env.PUBLIC_PATH,
}),
output: 'json/manifest.json',
}),
],
});
if (process.env.BUILD_TARGET === 'chrome-ext') {
webpackConfigs.push({
entry: utils.fullPath('src/entry/chrome-ext.ts'),
plugins: [
new CopyWebpackPlugin({
patterns: [
{
from: utils.fullPath('src/extra/chrome-ext/manifest.json'),
to: './',
filter: pathname => !pathname.endsWith('/.gitkeep'),
},
],
}),
],
});
} else {
webpackConfigs.push({
plugins: [
// auto generate service worker
new GenerateSW({
cacheId: packageConfig.name,
swDest: 'service-worker.js',
dontCacheBustURLsMatching: /static\//u,
exclude: [/\.html$/u, /\.map$/u, /\.json$/u],
runtimeCaching: [
{
urlPattern: /\/(m\/static)/u,
handler: 'NetworkFirst',
},
],
}),
],
});
}
}
if (process.env.ESLINT !== 'N') {
webpackConfigs.push({
plugins: [
plugins.eslintPlugin({
cache: false,
failOnError: !utils.isRun,
}),
],
});
}
if (process.env.STYLELINT !== 'N') {
webpackConfigs.push({
plugins: [
plugins.stylelintPlugin({
failOnError: !utils.isRun,
}),
],
});
}
if (process.env.REPORT === 'Y' && !utils.isRun) {
webpackConfigs.push({
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
}),
],
});
}
let webpackConfig = merge(webpackConfigs);
if (process.env.REPORT === 'Y' && !utils.isRun) {
const smp = new SpeedMeasurePlugin();
webpackConfig = smp.wrap(webpackConfig);
}
// SpeedMeasurePlugin conflict with MiniCssExtractPlugin.
// https://github.com/stephencookdev/speed-measure-webpack-plugin/issues/167#issuecomment-1040022776
webpackConfig.plugins.push(
new MiniCssExtractPlugin({
filename: 'css/[name].[chunkhash:4].css',
chunkFilename: 'css/[name].[chunkhash:4].css',
ignoreOrder: true,
}),
);
module.exports = webpackConfig;