-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
webpack.config.js
534 lines (476 loc) · 16.3 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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
require(`v8-compile-cache`)
const fs = require(`fs-extra`)
const path = require(`path`)
const dotenv = require(`dotenv`)
const FriendlyErrorsWebpackPlugin = require(`@pieh/friendly-errors-webpack-plugin`)
const PnpWebpackPlugin = require(`pnp-webpack-plugin`)
const { store } = require(`../redux`)
const { actions } = require(`../redux/actions`)
const getPublicPath = require(`./get-public-path`)
const debug = require(`debug`)(`gatsby:webpack-config`)
const report = require(`gatsby-cli/lib/reporter`)
const { withBasePath, withTrailingSlash } = require(`./path`)
const apiRunnerNode = require(`./api-runner-node`)
const createUtils = require(`./webpack-utils`)
const hasLocalEslint = require(`./local-eslint-config-finder`)
// Four stages or modes:
// 1) develop: for `gatsby develop` command, hot reload and CSS injection into page
// 2) develop-html: same as develop without react-hmre in the babel config for html renderer
// 3) build-javascript: Build JS and CSS chunks for production
// 4) build-html: build all HTML files
module.exports = async (program, directory, suppliedStage) => {
const directoryPath = withBasePath(directory)
process.env.GATSBY_BUILD_STAGE = suppliedStage
// We combine develop & develop-html stages for purposes of generating the
// webpack config.
const stage = suppliedStage
const { rules, loaders, plugins } = await createUtils({ stage, program })
const { assetPrefix, pathPrefix } = store.getState().config
const publicPath = getPublicPath({ assetPrefix, pathPrefix, ...program })
function processEnv(stage, defaultNodeEnv) {
debug(`Building env for "${stage}"`)
// node env should be DEVELOPMENT | PRODUCTION as these are commonly used in node land
// this variable is used inside webpack
const nodeEnv = process.env.NODE_ENV || `${defaultNodeEnv}`
// config env is depednant on the env that it's run, this can be anything from staging-production
// this allows you to set use different .env environments or conditions in gatsby files
const configEnv = process.env.GATSBY_ACTIVE_ENV || nodeEnv
const envFile = path.join(process.cwd(), `./.env.${configEnv}`)
let parsed = {}
try {
parsed = dotenv.parse(fs.readFileSync(envFile, { encoding: `utf8` }))
} catch (err) {
if (err.code !== `ENOENT`) {
report.error(
`There was a problem processing the .env file (${envFile})`,
err
)
}
}
const envObject = Object.keys(parsed).reduce((acc, key) => {
acc[key] = JSON.stringify(parsed[key])
return acc
}, {})
const gatsbyVarObject = Object.keys(process.env).reduce((acc, key) => {
if (key.match(/^GATSBY_/)) {
acc[key] = JSON.stringify(process.env[key])
}
return acc
}, {})
// Don't allow overwriting of NODE_ENV, PUBLIC_DIR as to not break gatsby things
envObject.NODE_ENV = JSON.stringify(nodeEnv)
envObject.PUBLIC_DIR = JSON.stringify(`${process.cwd()}/public`)
envObject.BUILD_STAGE = JSON.stringify(stage)
envObject.CYPRESS_SUPPORT = JSON.stringify(process.env.CYPRESS_SUPPORT)
const mergedEnvVars = Object.assign(envObject, gatsbyVarObject)
return Object.keys(mergedEnvVars).reduce(
(acc, key) => {
acc[`process.env.${key}`] = mergedEnvVars[key]
return acc
},
{
"process.env": JSON.stringify({}),
}
)
}
function getHmrPath() {
// ref: https://github.com/gatsbyjs/gatsby/issues/8348
let hmrBasePath = `/`
const hmrSuffix = `__webpack_hmr&reload=true&overlay=false`
if (process.env.GATSBY_WEBPACK_PUBLICPATH) {
const pubPath = process.env.GATSBY_WEBPACK_PUBLICPATH
if (pubPath.substr(-1) === `/`) {
hmrBasePath = pubPath
} else {
hmrBasePath = withTrailingSlash(pubPath)
}
}
return hmrBasePath + hmrSuffix
}
debug(`Loading webpack config for stage "${stage}"`)
function getOutput() {
switch (stage) {
case `develop`:
return {
path: directory,
filename: `[name].js`,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// Point sourcemap entries to original disk location (format as URL on Windows)
publicPath: process.env.GATSBY_WEBPACK_PUBLICPATH || `/`,
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, `/`),
// Avoid React cross-origin errors
// See https://reactjs.org/docs/cross-origin-errors.html
crossOriginLoading: `anonymous`,
}
case `build-html`:
case `develop-html`:
// A temp file required by static-site-generator-plugin. See plugins() below.
// Deleted by build-html.js, since it's not needed for production.
return {
path: directoryPath(`public`),
filename: `render-page.js`,
libraryTarget: `umd`,
library: `lib`,
umdNamedDefine: true,
globalObject: `this`,
publicPath: withTrailingSlash(publicPath),
}
case `build-javascript`:
return {
filename: `[name]-[contenthash].js`,
chunkFilename: `[name]-[contenthash].js`,
path: directoryPath(`public`),
publicPath: withTrailingSlash(publicPath),
}
default:
throw new Error(`The state requested ${stage} doesn't exist.`)
}
}
function getEntry() {
switch (stage) {
case `develop`:
return {
commons: [
require.resolve(`event-source-polyfill`),
`${require.resolve(
`webpack-hot-middleware/client`
)}?path=${getHmrPath()}`,
directoryPath(`.cache/app`),
],
}
case `develop-html`:
return {
main: directoryPath(`.cache/develop-static-entry`),
}
case `build-html`:
return {
main: directoryPath(`.cache/static-entry`),
}
case `build-javascript`:
return {
app: directoryPath(`.cache/production-app`),
}
default:
throw new Error(`The state requested ${stage} doesn't exist.`)
}
}
function getPlugins() {
let configPlugins = [
plugins.moment(),
// Add a few global variables. Set NODE_ENV to production (enables
// optimizations for React) and what the link prefix is (__PATH_PREFIX__).
plugins.define({
...processEnv(stage, `development`),
__BASE_PATH__: JSON.stringify(program.prefixPaths ? pathPrefix : ``),
__PATH_PREFIX__: JSON.stringify(program.prefixPaths ? publicPath : ``),
__ASSET_PREFIX__: JSON.stringify(
program.prefixPaths ? assetPrefix : ``
),
}),
]
switch (stage) {
case `develop`:
configPlugins = configPlugins.concat([
plugins.hotModuleReplacement(),
plugins.noEmitOnErrors(),
new FriendlyErrorsWebpackPlugin({
clearConsole: false,
}),
])
break
case `build-javascript`: {
configPlugins = configPlugins.concat([
plugins.extractText(),
// Write out stats object mapping named dynamic imports (aka page
// components) to all their async chunks.
plugins.extractStats(),
])
break
}
}
return configPlugins
}
function getDevtool() {
switch (stage) {
case `develop`:
return `cheap-module-source-map`
// use a normal `source-map` for the html phases since
// it gives better line and column numbers
case `develop-html`:
case `build-html`:
case `build-javascript`:
return `source-map`
default:
return false
}
}
function getMode() {
switch (stage) {
case `build-javascript`:
return `production`
case `develop`:
case `develop-html`:
case `build-html`:
return `development` // So we don't uglify the html bundle
default:
return `production`
}
}
function getModule() {
const jsOptions = {}
// Common config for every env.
// prettier-ignore
let configRules = [
rules.js(jsOptions),
rules.yaml(),
rules.fonts(),
rules.images(),
rules.media(),
rules.miscAssets(),
]
// Speedup 🏎️💨 the build! We only include transpilation of node_modules on javascript production builds
// TODO create gatsby plugin to enable this behaviour on develop (only when people are requesting this feature)
if (stage === `build-javascript`) {
configRules.push(rules.dependencies())
}
if (store.getState().themes.themes) {
configRules = configRules.concat(
store.getState().themes.themes.map(theme => {
return {
test: /\.jsx?$/,
include: theme.themeDir,
use: [loaders.js()],
}
})
)
}
switch (stage) {
case `develop`: {
// get schema to pass to eslint config and program for directory
const { schema, program } = store.getState()
// if no local eslint config, then add gatsby config
if (!hasLocalEslint(program.directory)) {
configRules = configRules.concat([rules.eslint(schema)])
}
configRules = configRules.concat([
{
oneOf: [rules.cssModules(), rules.css()],
},
])
// RHL will patch React, replace React-DOM by React-🔥-DOM and work with fiber directly
// It's necessary to remove the warning in console (https://github.com/gatsbyjs/gatsby/issues/11934)
configRules.push({
include: /node_modules/,
test: /\.jsx?$/,
use: {
loader: require.resolve(`./webpack-hmr-hooks-patch`),
},
})
break
}
case `build-html`:
case `develop-html`:
// We don't deal with CSS at all when building the HTML.
// The 'null' loader is used to prevent 'module not found' errors.
// On the other hand CSS modules loaders are necessary.
// prettier-ignore
configRules = configRules.concat([
{
oneOf: [
rules.cssModules(),
{
...rules.css(),
use: [loaders.null()],
},
],
},
])
break
case `build-javascript`:
// We don't deal with CSS at all when building JavaScript but we still
// need to process the CSS so offline-plugin knows about the various
// assets referenced in your CSS.
//
// It's also necessary to process CSS Modules so your JS knows the
// classNames to use.
configRules = configRules.concat([
{
oneOf: [rules.cssModules(), rules.css()],
},
])
break
}
return { rules: configRules }
}
function getResolve() {
const { program } = store.getState()
return {
// Use the program's extension list (generated via the
// 'resolvableExtensions' API hook).
extensions: [...program.extensions],
alias: {
gatsby$: directoryPath(path.join(`.cache`, `gatsby-browser-entry.js`)),
// Using directories for module resolution is mandatory because
// relative path imports are used sometimes
// See https://stackoverflow.com/a/49455609/6420957 for more details
"@babel/runtime": path.dirname(
require.resolve(`@babel/runtime/package.json`)
),
"core-js": path.dirname(require.resolve(`core-js/package.json`)),
"react-hot-loader": path.dirname(
require.resolve(`react-hot-loader/package.json`)
),
"react-lifecycles-compat": directoryPath(
`.cache/react-lifecycles-compat.js`
),
"create-react-context": directoryPath(`.cache/create-react-context.js`),
},
plugins: [
// Those two folders are special and contain gatsby-generated files
// whose dependencies should be resolved through the `gatsby` package
PnpWebpackPlugin.bind(directoryPath(`.cache`), module),
PnpWebpackPlugin.bind(directoryPath(`public`), module),
// Transparently resolve packages via PnP when needed; noop otherwise
PnpWebpackPlugin,
],
}
}
function getResolveLoader() {
const root = [path.resolve(directory, `node_modules`)]
const userLoaderDirectoryPath = path.resolve(directory, `loaders`)
try {
if (fs.statSync(userLoaderDirectoryPath).isDirectory()) {
root.push(userLoaderDirectoryPath)
}
} catch (err) {
debug(`Error resolving user loaders directory`, err)
}
return {
modules: [...root, path.join(__dirname, `../loaders`), `node_modules`],
// Bare loaders should always be loaded via the user dependencies (loaders
// configured via third-party like gatsby use require.resolve)
plugins: [PnpWebpackPlugin.moduleLoader(`${directory}/`)],
}
}
const config = {
// Context is the base directory for resolving the entry option.
context: directory,
entry: getEntry(),
output: getOutput(),
module: getModule(),
plugins: getPlugins(),
// Certain "isomorphic" packages have different entry points for browser
// and server (see
// https://github.com/defunctzombie/package-browser-field-spec); setting
// the target tells webpack which file to include, ie. browser vs main.
target: stage === `build-html` || stage === `develop-html` ? `node` : `web`,
devtool: getDevtool(),
// Turn off performance hints as we (for now) don't want to show the normal
// webpack output anywhere.
performance: {
hints: false,
},
mode: getMode(),
resolveLoader: getResolveLoader(),
resolve: getResolve(),
node: {
__filename: true,
},
}
if (stage === `build-javascript`) {
config.optimization = {
runtimeChunk: {
name: `webpack-runtime`,
},
splitChunks: {
name: false,
cacheGroups: {
// Only create one CSS file to avoid
// problems with code-split CSS loading in different orders
// causing inconsistent/non-determanistic styling
// See https://github.com/gatsbyjs/gatsby/issues/11072
styles: {
name: `styles`,
// This should cover all our types of CSS.
test: /\.(css|scss|sass|less|styl)$/,
chunks: `all`,
enforce: true,
},
},
},
minimizer: [
// TODO: maybe this option should be noMinimize?
!program.noUglify && plugins.minifyJs(),
plugins.minifyCss(),
].filter(Boolean),
}
}
if (stage === `build-html` || stage === `develop-html`) {
// Packages we want to externalize to save some build time
// https://github.com/gatsbyjs/gatsby/pull/14208#pullrequestreview-240178728
const externalList = [
`@reach/router/lib/history`,
`@reach/router`,
`common-tags`,
/^core-js\//,
`crypto`,
`debug`,
`fs`,
`https`,
`http`,
`lodash`,
`path`,
`semver`,
/^lodash\//,
`zlib`,
]
// Packages we want to externalize because meant to be user-provided
const userExternalList = [
`es6-promise`,
`minimatch`,
`pify`,
`react-helmet`,
`react`,
/^react-dom\//,
]
const checkItem = (item, request) => {
if (typeof item === `string` && item === request) {
return true
} else if (item instanceof RegExp && item.test(request)) {
return true
}
return false
}
const isExternal = request => {
if (externalList.some(item => checkItem(item, request))) {
return `umd ${require.resolve(request)}`
}
if (userExternalList.some(item => checkItem(item, request))) {
return `umd ${request}`
}
return null
}
config.externals = [
function(context, request, callback) {
const external = isExternal(request)
if (external !== null) {
callback(null, external)
} else {
callback()
}
},
]
}
store.dispatch(actions.replaceWebpackConfig(config))
const getConfig = () => store.getState().webpack
await apiRunnerNode(`onCreateWebpackConfig`, {
getConfig,
stage,
rules,
loaders,
plugins,
})
return getConfig()
}