-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathwebpack.config.js
491 lines (438 loc) · 14 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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import fs from 'fs';
import path from 'path';
import webpack from 'webpack';
import WebpackAssetsManifest from 'webpack-assets-manifest';
import nodeExternals from 'webpack-node-externals';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import overrideRules from './lib/overrideRules';
import pkg from '../package.json';
const ROOT_DIR = path.resolve(__dirname, '..');
const resolvePath = (...args) => path.resolve(ROOT_DIR, ...args);
const SRC_DIR = resolvePath('src');
const BUILD_DIR = resolvePath('build');
const isDebug = !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose');
const isAnalyze =
process.argv.includes('--analyze') || process.argv.includes('--analyse');
const reScript = /\.(js|jsx|mjs)$/;
const reStyle = /\.(css|less|styl|scss|sass|sss)$/;
const reImage = /\.(bmp|gif|jpg|jpeg|png|svg)$/;
const staticAssetName = isDebug
? '[path][name].[ext]?[hash:8]'
: '[hash:8].[ext]';
//
// Common configuration chunk to be used for both
// client-side (client.js) and server-side (server.js) bundles
// -----------------------------------------------------------------------------
const config = {
context: ROOT_DIR,
mode: isDebug ? 'development' : 'production',
output: {
path: resolvePath(BUILD_DIR, 'public/assets'),
publicPath: '/assets/',
pathinfo: isVerbose,
filename: isDebug ? '[name].js' : '[name].[chunkhash:8].js',
chunkFilename: isDebug
? '[name].chunk.js'
: '[name].[chunkhash:8].chunk.js',
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
resolve: {
// Allow absolute paths in imports, e.g. import Button from 'components/Button'
// Keep in sync with .flowconfig and .eslintrc
modules: ['node_modules', 'src'],
},
module: {
// Make missing exports an error instead of warning
strictExportPresence: true,
rules: [
// Rules for JS / JSX
{
test: reScript,
include: [SRC_DIR, resolvePath('tools')],
loader: 'babel-loader',
options: {
// /~https://github.com/babel/babel-loader#options
cacheDirectory: isDebug,
// https://babeljs.io/docs/usage/options/
babelrc: false,
configFile: false,
presets: [
// A Babel preset that can automatically determine the Babel plugins and polyfills
// /~https://github.com/babel/babel-preset-env
[
'@babel/preset-env',
{
targets: {
browsers: pkg.browserslist,
},
forceAllTransforms: !isDebug, // for UglifyJS
modules: false,
useBuiltIns: false,
debug: false,
},
],
// Flow
// /~https://github.com/babel/babel/tree/master/packages/babel-preset-flow
'@babel/preset-flow',
// JSX
// /~https://github.com/babel/babel/tree/master/packages/babel-preset-react
['@babel/preset-react', { development: isDebug }],
],
plugins: [
// Experimental ECMAScript proposals
'@babel/plugin-proposal-class-properties',
'@babel/plugin-syntax-dynamic-import',
// Treat React JSX elements as value types and hoist them to the highest scope
// /~https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-constant-elements
...(isDebug ? [] : ['@babel/transform-react-constant-elements']),
// Replaces the React.createElement function with one that is more optimized for production
// /~https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-inline-elements
...(isDebug ? [] : ['@babel/transform-react-inline-elements']),
// Remove unnecessary React propTypes from the production build
// /~https://github.com/oliviertassinari/babel-plugin-transform-react-remove-prop-types
...(isDebug ? [] : ['transform-react-remove-prop-types']),
],
},
},
// Rules for Style Sheets
{
test: reStyle,
rules: [
// Convert CSS into JS module
{
issuer: { not: [reStyle] },
use: 'isomorphic-style-loader',
},
// Process external/third-party styles
{
exclude: SRC_DIR,
loader: 'css-loader',
options: {
sourceMap: isDebug,
},
},
// Process internal/project styles (from src folder)
{
include: SRC_DIR,
loader: 'css-loader',
options: {
// CSS Loader /~https://github.com/webpack/css-loader
importLoaders: 1,
sourceMap: isDebug,
// CSS Modules /~https://github.com/css-modules/css-modules
modules: {
localIdentName: isDebug
? '[name]-[local]-[hash:base64:5]'
: '[hash:base64:5]',
},
},
},
// Apply PostCSS plugins including autoprefixer
{
loader: 'postcss-loader',
options: {
config: {
path: './tools/postcss.config.js',
},
},
},
// Compile Less to CSS
// /~https://github.com/webpack-contrib/less-loader
// Install dependencies before uncommenting: yarn add --dev less-loader less
// {
// test: /\.less$/,
// loader: 'less-loader',
// },
// Compile Sass to CSS
// /~https://github.com/webpack-contrib/sass-loader
// Install dependencies before uncommenting: yarn add --dev sass-loader node-sass
// {
// test: /\.(scss|sass)$/,
// loader: 'sass-loader',
// },
],
},
// Rules for images
{
test: reImage,
oneOf: [
// Inline lightweight images into CSS
{
issuer: reStyle,
oneOf: [
// Inline lightweight SVGs as UTF-8 encoded DataUrl string
{
test: /\.svg$/,
loader: 'svg-url-loader',
options: {
name: staticAssetName,
limit: 4096, // 4kb
},
},
// Inline lightweight images as Base64 encoded DataUrl string
{
loader: 'url-loader',
options: {
name: staticAssetName,
limit: 4096, // 4kb
},
},
],
},
// Or return public URL to image resource
{
loader: 'file-loader',
options: {
name: staticAssetName,
},
},
],
},
// Convert plain text into JS module
{
test: /\.txt$/,
loader: 'raw-loader',
},
// Convert Markdown into HTML
{
test: /\.md$/,
loader: path.resolve(__dirname, './lib/markdown-loader.js'),
},
// Return public URL for all assets unless explicitly excluded
// DO NOT FORGET to update `exclude` list when you adding a new loader
{
exclude: [reScript, reStyle, reImage, /\.json$/, /\.txt$/, /\.md$/],
loader: 'file-loader',
options: {
name: staticAssetName,
},
},
// Exclude dev modules from production build
...(isDebug
? []
: [
{
test: resolvePath(
'node_modules/react-deep-force-update/lib/index.js',
),
loader: 'null-loader',
},
]),
],
},
// Don't attempt to continue if there are any errors.
bail: !isDebug,
cache: isDebug,
// Specify what bundle information gets displayed
// https://webpack.js.org/configuration/stats/
stats: {
cached: isVerbose,
cachedAssets: isVerbose,
chunks: isVerbose,
chunkModules: isVerbose,
colors: true,
hash: isVerbose,
modules: isVerbose,
reasons: isDebug,
timings: true,
version: isVerbose,
},
// Choose a developer tool to enhance debugging
// https://webpack.js.org/configuration/devtool/#devtool
devtool: isDebug ? 'cheap-module-inline-source-map' : 'source-map',
};
//
// Configuration for the client-side bundle (client.js)
// -----------------------------------------------------------------------------
const clientConfig = {
...config,
name: 'client',
target: 'web',
entry: {
client: ['@babel/polyfill', './src/client.js'],
},
plugins: [
// Define free variables
// https://webpack.js.org/plugins/define-plugin/
new webpack.DefinePlugin({
'process.env.BROWSER': true,
__DEV__: isDebug,
}),
// Emit a file with assets paths
// /~https://github.com/webdeveric/webpack-assets-manifest#options
new WebpackAssetsManifest({
output: `${BUILD_DIR}/asset-manifest.json`,
publicPath: true,
writeToDisk: true,
customize: ({ key, value }) => {
// You can prevent adding items to the manifest by returning false.
if (key.toLowerCase().endsWith('.map')) return false;
return { key, value };
},
done: (manifest, stats) => {
// Write chunk-manifest.json.json
const chunkFileName = `${BUILD_DIR}/chunk-manifest.json`;
try {
const fileFilter = file => !file.endsWith('.map');
const addPath = file => manifest.getPublicPath(file);
const chunkFiles = stats.compilation.chunkGroups.reduce((acc, c) => {
acc[c.name] = [
...(acc[c.name] || []),
...c.chunks.reduce(
(files, cc) => [
...files,
...cc.files.filter(fileFilter).map(addPath),
],
[],
),
];
return acc;
}, Object.create(null));
fs.writeFileSync(chunkFileName, JSON.stringify(chunkFiles, null, 2));
} catch (err) {
console.error(`ERROR: Cannot write ${chunkFileName}: `, err);
if (!isDebug) process.exit(1);
}
},
}),
...(isDebug
? []
: [
// Webpack Bundle Analyzer
// /~https://github.com/th0r/webpack-bundle-analyzer
...(isAnalyze ? [new BundleAnalyzerPlugin()] : []),
]),
],
// Move modules that occur in multiple entry chunks to a new entry chunk (the commons chunk).
optimization: {
splitChunks: {
cacheGroups: {
commons: {
chunks: 'initial',
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
},
},
},
},
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
// https://webpack.js.org/configuration/node/
// /~https://github.com/webpack/node-libs-browser/tree/master/mock
node: {
fs: 'empty',
net: 'empty',
tls: 'empty',
},
};
//
// Configuration for the server-side bundle (server.js)
// -----------------------------------------------------------------------------
const serverConfig = {
...config,
name: 'server',
target: 'node',
entry: {
server: ['@babel/polyfill', './src/server.js'],
},
output: {
...config.output,
path: BUILD_DIR,
filename: '[name].js',
chunkFilename: 'chunks/[name].js',
libraryTarget: 'commonjs2',
},
// Webpack mutates resolve object, so clone it to avoid issues
// /~https://github.com/webpack/webpack/issues/4817
resolve: {
...config.resolve,
},
module: {
...config.module,
rules: overrideRules(config.module.rules, rule => {
// Override babel-preset-env configuration for Node.js
if (rule.loader === 'babel-loader') {
return {
...rule,
options: {
...rule.options,
presets: rule.options.presets.map(preset =>
preset[0] !== '@babel/preset-env'
? preset
: [
'@babel/preset-env',
{
targets: {
node: pkg.engines.node.match(/(\d+\.?)+/)[0],
},
modules: false,
useBuiltIns: false,
debug: false,
},
],
),
},
};
}
// Override paths to static assets
if (
rule.loader === 'file-loader' ||
rule.loader === 'url-loader' ||
rule.loader === 'svg-url-loader'
) {
return {
...rule,
options: {
...rule.options,
emitFile: false,
},
};
}
return rule;
}),
},
externals: [
'./chunk-manifest.json',
'./asset-manifest.json',
nodeExternals({
whitelist: [reStyle, reImage],
}),
],
plugins: [
// Define free variables
// https://webpack.js.org/plugins/define-plugin/
new webpack.DefinePlugin({
'process.env.BROWSER': false,
__DEV__: isDebug,
}),
// Adds a banner to the top of each generated chunk
// https://webpack.js.org/plugins/banner-plugin/
new webpack.BannerPlugin({
banner: 'require("source-map-support").install();',
raw: true,
entryOnly: false,
}),
],
// Do not replace node globals with polyfills
// https://webpack.js.org/configuration/node/
node: {
console: false,
global: false,
process: false,
Buffer: false,
__filename: false,
__dirname: false,
},
};
export default [clientConfig, serverConfig];