-
Notifications
You must be signed in to change notification settings - Fork 0
/
webpack.config.js
486 lines (433 loc) · 14.7 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
require('dotenv').config({ path: `${__dirname}/.env` }) // https://goo.gl/Cj8nKu
const { NODE_ENV, DEV_SERVER_PORT, API, API_PORT, API_WEBPACK } = process.env
const path = require('path')
const webpack = require('webpack')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const AfterCompilePlugin = require('./after-compile-plugin')
console.log(`
+-----------------------------------+
| |
NODE ENVIRONMENT: ${NODE_ENV}
| |
+-----------------------------------+
`)
if (NODE_ENV === 'production') console.log('Building for production...\n\n')
module.exports = (env, argv) => ({
// https://goo.gl/R88FtY - new in Webpack 4.
mode: env.prod ? 'production' : 'development',
/*
https://goo.gl/3FP7kM
The base directory, an absolute path, for resolving
entry points and loaders from configuration.
*/
context: path.resolve(__dirname, 'src'),
/*
https://goo.gl/X8nHJZ
The point(s) to enter the application.
*/
entry: [
path.resolve(__dirname, 'src/entry.js')
],
/*
https://goo.gl/xvjXJd
The top-level output key contains set of options instructing webpack
on how and where it should output your bundles, assets and anything else
you bundle or load with webpack.
*/
output: {
/*
https://goo.gl/DsD2Nn
This option determines the name of each output bundle.
*/
filename: '[name].bundle.js',
/*
https://goo.gl/bwR2sW
The output directory as an absolute path.
*/
path: path.resolve(__dirname, 'dist'),
/*
https://goo.gl/d6Wq2G
Adds helpful info in development when reading the generated code.
*/
pathinfo: !env.prod,
/*
https://goo.gl/jvYGYt
The URL of your `output.path` from the view of the HTML page.
The value of the option is prefixed to every URL created by the runtime or loaders.
*/
publicPath: '/'
},
/*
https://goo.gl/AENyuH
These options determine how the different types of modules within a project will be treated.
*/
module: {
/*
An array of Rules which are matched to requests when modules are created.
These rules can modify how the module is created.
They can apply loaders to the module, or modify the parser.
*/
rules: [
/*
https://goo.gl/aq8Jce
A Rule can be separated into three parts — Conditions, Results and nested Rules.
Conditions (https://goo.gl/9wzXt9)
----------
In a Rule the properties `test`, `include`, `exclude` and `resource` are
matched with the resource and the property issuer is matched with the issuer.
-------- ------
When we import './style.css' within app.js,
the resource is /path/to/style.css and the issuer is /path/to/app.js.
Results
-------
There are two output values of a Rule:
1. Applied loaders
- An array of loaders applied to the resource.
- Properties: `loader`, `options`, `use`.
- The `enforce` property affects the loader category. Whether it's a normal, pre- or post- loader.
2. Parser options
- An options object which should be used to create the parser for this module.
- Properties: `parser`.
Nested Rules
------------
Nested rules can be specified under the properties `rules` and `oneOf`.
These rules are evaluated when the Rule condition matches.
*/
/*
JAVASCRIPT
----------
* ESx => ES5
* JSX => ES5
*/
{
// sideEffects: false,
test: /\.(js|jsx)$/,
include: path.resolve(__dirname, 'src'),
/*
https://goo.gl/99S6sU
Loaders will be applied from right to left.
E.x.: loader3(loader2(loader1(data)))
*/
use: [
// https://goo.gl/EXjzoG
{
/*
https://goo.gl/N6uJv3 - Babel loader.
- babel-loader
- @babel/core
- @babel/preset-env
- @babel/preset-react
- @babel/plugin-proposal-object-rest-spread
- @babel/plugin-proposal-class-properties
- @babel/plugin-syntax-dynamic-import
*/
loader: 'babel-loader',
options: {
presets: [
/*
To get tree shaking working, we need the `modules: false` below.
https://goo.gl/4vZBSr - 2ality blog mentions that the issue is caused
by under-the-hood usage of `transform-es2015-modules-commonjs`.
https://goo.gl/sBmiwZ - A comment on the above post shows that we
can use `modules: false`.
*/
[
'@babel/preset-env', // https://goo.gl/aAxYAq
{
modules: false, // Needed for tree shaking to work (see above).
useBuiltIns: 'entry', // https://goo.gl/7ugJ8K
corejs: { // https://goo.gl/9Vfu6X
version: 3,
proposals: true
}
}
],
'@babel/preset-react' // https://goo.gl/4aEFV3
],
// https://goo.gl/N9gaqc - List of Babel plugins.
plugins: [
'@babel/plugin-proposal-object-rest-spread', // https://goo.gl/LCHWnP
'@babel/plugin-proposal-class-properties', // https://goo.gl/TE6TyG
'@babel/plugin-syntax-dynamic-import' // https://goo.gl/ho4CDh
]
}
}
]
},
/*
SCSS
----
* SCSS => CSS
* Extract CSS from JS bundle => separate asset
* Asset => <link> in index.html
*/
{
test: /\.(scss|css)$/,
include: path.resolve(__dirname, 'src'),
use: [
MiniCssExtractPlugin.loader, // https://goo.gl/uUBr8G
{
/*
https://goo.gl/L44Kxn
Using `fast-css-loader` combined with `fast-sass-loader` (below)
produces about a 50% faster build. You'll notice it while developing.
`css-loader` is still included so feel free to switch.
*/
loader: 'fast-css-loader',
options: {
importLoaders: 2
}
},
'postcss-loader', // https://goo.gl/BCwCzg - needs to be *after* `css-loader`.
{
/*
https://goo.gl/GtngkV
Using `fast-sass-loader` combined with `fast-css-loader` (above)
produces about a 50% faster build. You'll notice it while developing.
`sass-loader` is still included so feel free to switch.
*/
loader: 'fast-sass-loader',
options: {
/*
https://goo.gl/hVweJ7
An array of paths that in which to attempt to resolve your
@import declarations made in your scss files.
*/
includePaths: [
'node_modules/sassyons'
],
/*
https://goo.gl/xxBHk3
Values: nested, expanded, compact, compressed
*/
outputStyle: env.prod ? 'compressed' : 'expanded'
}
}
]
},
/*
FONTS
-----
* Copies fonts found within the `src` tree to the `dist` folder
* Keeps the original file name
*/
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
include: path.resolve(__dirname, 'src'),
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]'
}
}
]
},
{
test: /\.css$/,
include: /node_modules/,
loaders: ['style-loader', 'css-loader'],
},
/*
IMAGES
------
* Copies fonts found within the `src` tree to the `dist` folder
* Keeps the original file name
*/
{
test: /\.(png|svg|jpg|gif)$/,
include: path.resolve(__dirname, 'src/assets'),
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]'
}
}
]
}
]
},
// https://goo.gl/NnR9ME
resolve: {
/*
https://goo.gl/7HMoAb
Create aliases to import certain modules more easily.
Eliminates having to type out ../../../ all the time.
*/
alias: {
components: path.resolve(__dirname, 'src/components'),
assets: path.resolve(__dirname, 'src/assets')
},
/*
https://goo.gl/57vTmD
Automatically resolve certain extensions without having to type them out.
*/
extensions: ['.js', '.jsx', '.json', '.scss']
},
// https://goo.gl/bxPV7L
optimization: {
minimizer: [
// https://goo.gl/yWD5vm - List of reasons we're using Terser instead (Webpack is too!).
new TerserPlugin({ // https://goo.gl/YgdtKb
cache: true, // https://goo.gl/QVWRtq
parallel: true, //https://goo.gl/hUkvnK
terserOptions: { // https://goo.gl/y3psR1
ecma: 5,
output: {
comments: false
}
}
})
]
},
// https://goo.gl/aDKWnb
plugins: [
/*
https://goo.gl/SZjjmC
Make global variables available to the app.
Needed in order to use the production-ready minified version of React.
*/
new webpack.DefinePlugin({
// Convenience variables.
__DEV__: !env.prod,
__PROD__: env.prod,
/*
https://goo.gl/sB6d6b
Needed in order to use the production-ready minified version of React.
Avoids warnings in the console.
*/
'process.env': {
NODE_ENV: JSON.stringify(env.prod ? 'production' : 'development')
}
}),
// This must be used in conjunction with the associated scss module rule.
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// Both options are optional.
filename: '[name].css',
chunkFilename: '[id].css'
}),
/*
https://goo.gl/xP7eDB
A webpack plugin to remove/clean your build folder(s) before building.
The targeted folder is whatever is set above for `output.path`.
Since our build process generates a js, css, and html file, we'll only
clean those types. This allows you to put any other static assets in the
`dist` folder worry free, such as fonts, images, etc.
*/
new CleanWebpackPlugin({
verbose: true,
cleanOnceBeforeBuildPatterns: ['*.js', '*.css', '*.html'],
cleanAfterEveryBuildPatterns: ['*.js', '*.css', '*.html']
}),
/*
https://goo.gl/pwnnmX, https://goo.gl/og4sNK
Generates the `index.html` file.
*/
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src/index.ejs'),
title: '',
mobileThemeColor: '#000000',
description: '',
minify: {
collapseWhitespace: true,
removeComments: true
}
}),
/*
A simple, custom Webpack plugin to run a function after each build.
You can see the code in `after-compile-plugin.js` in the project root dir.
*/
!env.prod && new AfterCompilePlugin({
run: () => {
console.log('\n')
API && console.log(`🌎 => API listening on port ${API_PORT}...`)
console.log(`💻 => Application running in browser at http://localhost:${DEV_SERVER_PORT}\n\n`)
}
})
].filter(Boolean),
// https://goo.gl/HBnQlq
devServer: {
/*
https://goo.gl/eFdUfe
Tell the dev server where to serve content from.
This is only necessary if you want to serve static files.
Content not served from Webpack's devServer is served from here.
*/
contentBase: path.resolve(__dirname, 'dist'),
/*
https://goo.gl/mgQHiQ
'...the index.html page will likely have to be served
in place of any 404 responses.'
*/
historyApiFallback: true,
/*
https://goo.gl/A8ZvxG
Want to view your site on your phone?
Make sure your computer and phone are on the same wifi network,
and navigate to your computer's ip addres: 192.1.2.3:<dev server port>
*/
host: '0.0.0.0',
// https://goo.gl/fZ1Hff
open: true,
// https://goo.gl/EVMMyC
port: DEV_SERVER_PORT,
/*
https://goo.gl/mrysGp, https://goo.gl/srfqLB
Nobody wants to see 0.0.0.0 in the browser. This get's rid of that.
*/
public: `http://localhost:${DEV_SERVER_PORT}`,
/*
https://goo.gl/a6WW1p
Redirect non-static asset calls to the backend API server.
Unrecognized urls (non-API calls) will be directed to '/'.
404's will be served `index.html` by `historyApiFallback` above.
*/
proxy: API_WEBPACK ? {
[API_WEBPACK]: {
target: `http://localhost:${API_PORT}`,
bypass(req, res, proxyOptions) {
// Direct all non-get requests to the API server.
if (req.method.toLowerCase() !== 'get') return
/*
Proxy url (browser) requests back to '/'
and let the front end do all the routing.
For all others, let the API server respond.
*/
// Url / browser request - allow front end routing to handle all the things.
if ((req.headers.accept || '').includes('html')) return '/'
// Let the API server respond by implicitly returning here.
}
}
} : {}
},
/*
https://goo.gl/K4eZeE
Seems to be the fastest one with accurate line numbers
matching what you'd see in your editor.
*/
devtool: !env.prod && 'cheap-module-eval-source-map',
/*
https://goo.gl/ZisDCb
The externals configuration option provides a way of excluding dependencies
from the output bundles. Instead, the created bundle relies on that dependency
to be present in the consumer's environment.
If you want to load 3rd party libraries via a CDN instead of bundling them,
include them here in addition to adding `<script>` tags to `index.ejs`.
*/
// externals: {
// react: { root: 'react' },
// 'react-dom': { root: 'reactDOM' },
// // 'react-router-dom': { root: 'ReactRouterDOM' }
// },
/*
https://goo.gl/3mK5hF
`web` is default, but if you're making a 3rd party library
consumed in Node, change this to `node`. There are others as well.
*/
target: 'web'
})