-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebpack.config.js
473 lines (458 loc) · 16.4 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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
// const ESLintPlugin = require('eslint-webpack-plugin');
const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const { createHash } = require('crypto');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const autoPrefixer = require('autoprefixer');
const postcssNormalize = require('postcss-normalize');
const postCssPresetEnv = require('postcss-preset-env');
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
// const BundleAnalyzerPlugin =
// require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const CopyPlugin = require('copy-webpack-plugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const fs = require('fs');
const cloneDeep = require('lodash.clonedeep');
const evalSourceMapMiddleware = require('./evalSourceMapMiddleware');
const redirectServedPath = require('./redirectServedPathMiddleware');
const noopServiceWorkerMiddleware = require('./noopServiceWorkerMiddleware');
const envFilePath = path.resolve(__dirname, 'env.js');
const sourcePath = path.join(__dirname, 'src');
const assetsPath = path.join(sourcePath, 'assets');
const buildPath = path.join(__dirname, 'dist');
const getEnvHash = (env) => {
const hash = createHash('md5');
hash.update(JSON.stringify(env));
return hash.digest('hex');
};
module.exports = (env = {}, argv = {}) => {
const { mode = 'production' } = argv || {};
const envHash = getEnvHash({ ...env, argv });
const COMMIT_SHA = env.COMMIT_SHA || 'local';
const isProductionMode = mode === 'production';
const isDevelopmentMode = mode === 'development';
let envFileExists;
let config = {
mode,
bail: isProductionMode,
context: sourcePath,
devtool: isProductionMode ? 'source-map' : 'source-map',
entry: {
app: {
import: path.resolve(sourcePath, 'entrypoint.js'),
dependOn: 'vendor',
},
vendor: [
'react',
'react-dom',
isDevelopmentMode && 'react-refresh/runtime',
].filter(Boolean),
},
output: {
path: buildPath,
pathinfo: isDevelopmentMode,
filename: isProductionMode
? `${COMMIT_SHA}/assets/js/[name].[contenthash:8].js`
: isDevelopmentMode && `${COMMIT_SHA}/assets/js/[name].js`,
chunkFilename: isProductionMode
? `${COMMIT_SHA}/assets/js/[name]-[contenthash:8].chunk.js`
: isDevelopmentMode &&
`${COMMIT_SHA}/assets/js/[contenthash:8].chunk.js`,
assetModuleFilename: isProductionMode
? `${COMMIT_SHA}/assets/media/[name]-[contenthash:8][ext]`
: `${COMMIT_SHA}/assets/media/[name][ext]`,
cssChunkFilename: isProductionMode
? `${COMMIT_SHA}/assets/css/[id]-[contenthash:8].chunk.css`
: `${COMMIT_SHA}/assets/css/[id].chunk.css`,
cssFilename: isProductionMode
? `${COMMIT_SHA}/assets/css/[name]-[contenthash:8].css`
: `${COMMIT_SHA}/assets/css/[name].css`,
publicPath: '/',
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: isProductionMode
? (info) =>
path
.relative(sourcePath, info.absoluteResourcePath)
.replace(/\\/g, '/')
: (info) => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
cache: {
type: 'filesystem',
version: envHash,
cacheDirectory: path.join(__dirname, '.yarn/.cache'),
store: 'pack',
buildDependencies: {
defaultWebpack: ['webpack/lib/'],
config: [__filename],
},
},
// infrastructureLogging: {
// level: 'none',
// },
module: {
strictExportPresence: true,
rules: [
{
test: /\.(styl)$/,
use: [
isDevelopmentMode && 'css-hot-loader',
{
// Extracts CSS to a separate file
loader: MiniCssExtractPlugin.loader,
},
{
// Translates CSS into CommonJS
loader: 'css-loader',
},
{
loader: 'postcss-loader',
options: {
sourceMap: isProductionMode,
postcssOptions: {
config: false,
plugins: [
postCssPresetEnv,
autoPrefixer({
context: sourcePath,
}),
postcssNormalize(),
],
},
},
},
{
loader: 'stylus-native-loader',
},
].filter(Boolean),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
{
test: /\.css$/,
use: [
{
// Extracts CSS to a separate file
loader: MiniCssExtractPlugin.loader,
},
{
// Translates CSS into CommonJS
loader: 'css-loader',
},
{
loader: 'postcss-loader',
options: {
sourceMap: isProductionMode,
postcssOptions: {
config: false,
plugins: [
postCssPresetEnv,
autoPrefixer({
context: sourcePath,
}),
postcssNormalize(),
],
},
},
},
].filter(Boolean),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
{
test: /env\.js$/,
loader: 'file-loader',
generator: {
filename: 'env.js',
},
},
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: sourcePath,
use: [
{
loader: 'babel-loader',
options: {
exclude: [
// \\ for Windows, / for macOS and Linux
/.yarn[\\/]core-js/,
/.yarn[\\/]webpack[\\/]buildin/,
],
plugins: [
isDevelopmentMode && require.resolve('react-refresh/babel'),
].filter(Boolean),
// // This is a feature of `babel-loader` for webpack (not Babel itself).
// // It enables caching results in ./node_modules/.cache/babel-loader/
// // directory for faster rebuilds.
// cacheDirectory: true,
// // // See #6846 for context on why cacheCompression is disabled
// cacheCompression: false,
compact: isProductionMode,
},
},
],
},
{
test: /\.(jpe?g|svg|png|gif|ico|eot|ttf|woff2?)(\?v=\d+\.\d+\.\d+)?$/i,
exclude: [
/ckeditor5-[^/\\]+[/\\]theme[/\\]icons[/\\][^/\\]+\.svg$/,
/ckeditor5-[^/\\]+[/\\]theme[/\\].+\.css$/,
],
type: 'asset/resource',
generator: {
filename: `${COMMIT_SHA}/assets/media/[name]-[contenthash:8][ext][query]`,
},
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/^$/, /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
type: 'asset/resource',
},
],
},
resolve: {
alias: {
// moment: path.resolve(__dirname, '.yarn/moment/min/moment.min.js')
},
},
plugins: [
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment/,
}),
isDevelopmentMode && new CaseSensitivePathsPlugin(),
new RemoveEmptyScriptsPlugin({ enabled: isProductionMode === true }),
new webpack.DefinePlugin({
'process.env': Object.keys(env).reduce((envObject, key) => {
return { ...envObject, [key]: JSON.stringify(env[key]) };
}, {}),
}),
new HtmlWebpackPlugin({
template: path.resolve(assetsPath, 'index.html'),
filename: 'index.html',
inject: true,
...(isProductionMode
? {
minify: {
removeComments: true,
removeCommentsFromCDATA: true,
removeCDATASectionsFromCDATA: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeScriptTypeAttributes: true,
caseSensitive: true,
minifyJS: true,
minifyCSS: true,
},
}
: {}),
}),
isProductionMode &&
new FaviconsWebpackPlugin({
logo: path.resolve(assetsPath, 'favicon/logo.png'),
mode: 'webapp',
devMode: 'light',
cache: true,
inject: true,
prefix: 'favicon/',
publicPath: '/',
icons: {
android: false,
appleIcon: false,
appleStartup: false,
favicons: true,
windows: false,
yandex: false,
},
}),
isDevelopmentMode &&
new ReactRefreshWebpackPlugin({
overlay: false,
}),
new MiniCssExtractPlugin({
// runtime: false,
filename: isProductionMode
? `${COMMIT_SHA}/assets/css/[name].[contenthash:8].css`
: `${COMMIT_SHA}/assets/css/[name].css`,
chunkFilename: isProductionMode
? `${COMMIT_SHA}/assets/css/[id].[contenthash:8].css`
: `${COMMIT_SHA}/assets/css/[id].css`,
}),
new CopyPlugin({
patterns: [
{
from: path.resolve(sourcePath, 'assets/robots.txt'),
to: './',
},
{
from: envFilePath,
to: './',
},
],
}),
isProductionMode &&
new WebpackManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: '/',
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
const newManifest = cloneDeep(manifest);
newManifest[file.name] = file.path;
return newManifest;
}, seed);
const entrypointFiles = entrypoints.app.filter(
(fileName) => !fileName.endsWith('.map'),
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
isProductionMode &&
new WorkboxWebpackPlugin.InjectManifest({
swSrc: path.resolve(sourcePath, 'service-worker.js'),
dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./,
exclude: [/\.map$/, /asset-manifest\.json$/, /env\.js$/, /LICENSE/],
// Bump up the default maximum size (2mb) that's precached,
// to make lazy-loading failure scenarios less likely.
// See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
}),
isProductionMode && {
apply: (compiler) => {
compiler.hooks.beforeRun.tap('envManagerBeforeRun', () => {
if ((envFileExists = fs.existsSync(envFilePath))) return;
fs.copyFile(`${envFilePath}.example`, envFilePath, (err) => {
if (err) throw err;
console.log('env.js: stub created');
});
});
compiler.hooks.done.tap('envManagerAfterRun', () => {
if (envFileExists) return;
fs.unlink(envFilePath, (err) => {
if (err) throw err;
console.log('env.js: stub removed');
});
});
},
},
].filter(Boolean),
optimization: {
runtimeChunk: 'single',
minimize: isProductionMode,
minimizer: [
// This is only used in production mode
isProductionMode &&
new TerserPlugin({
terserOptions: {
parse: {
// We want terser to parse ecma 8 code. However, we don't want it
// to apply any minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Disabled because of an issue with Terser breaking valid code:
// https://github.com/facebook/create-react-app/issues/5250
// Pending further investigation:
// https://github.com/terser-js/terser/issues/120
inline: 2,
},
mangle: {
safari10: true,
},
// Added for profiling in devtools
keep_classnames: isProductionMode,
keep_fnames: isProductionMode,
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
}),
// This is only used in production mode
new CssMinimizerPlugin({
// exclude: /prism/,
minimizerOptions: {
plugins: ['autoprefixer', 'postcss-preset-env'],
minify: [
CssMinimizerPlugin.cssnanoMinify,
CssMinimizerPlugin.cleanCssMinify,
CssMinimizerPlugin.esbuildMinify,
],
preset: [
'default',
{
discardComments: false,
discardEmpty: false,
mergeIdents: true,
},
],
},
}),
].filter(Boolean),
},
};
if (isDevelopmentMode) {
config = {
...config,
devServer: {
client: { overlay: false },
historyApiFallback: true,
port: 5014,
hot: true,
setupMiddlewares: (middlewares, devServer) => {
if (!devServer) {
throw new Error('webpack-dev-server is not defined');
}
middlewares.push(
evalSourceMapMiddleware(devServer),
redirectServedPath('/'),
noopServiceWorkerMiddleware('/'),
);
return middlewares;
},
},
};
}
// config.plugins.push(new BundleAnalyzerPlugin());
return config;
};