/
webpack-utils.ts
737 lines (658 loc) · 19 KB
/
webpack-utils.ts
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
import * as path from "path"
import { Loader, RuleSetRule, Plugin } from "webpack"
import { GraphQLSchema } from "graphql"
import postcss from "postcss"
import autoprefixer from "autoprefixer"
import flexbugs from "postcss-flexbugs-fixes"
import TerserPlugin from "terser-webpack-plugin"
import MiniCssExtractPlugin from "mini-css-extract-plugin"
import OptimizeCssAssetsPlugin from "optimize-css-assets-webpack-plugin"
import ReactRefreshWebpackPlugin from "@pmmmwh/react-refresh-webpack-plugin"
import { getBrowsersList } from "./browserslist"
import semver from "semver"
import { GatsbyWebpackStatsExtractor } from "./gatsby-webpack-stats-extractor"
import { GatsbyWebpackEslintGraphqlSchemaReload } from "./gatsby-webpack-eslint-graphql-schema-reload-plugin"
import {
GatsbyWebpackVirtualModules,
VIRTUAL_MODULES_BASE_PATH,
} from "./gatsby-webpack-virtual-modules"
import { builtinPlugins } from "./webpack-plugins"
import { IProgram, Stage } from "../commands/types"
import { eslintConfig } from "./eslint-config"
type LoaderResolver<T = {}> = (options?: T) => Loader
type LoaderOptions = Record<string, any>
type RuleFactory<T = {}> = (options?: T & LoaderOptions) => RuleSetRule
type ContextualRuleFactory<T = {}> = RuleFactory<T> & {
internal?: RuleFactory<T>
external?: RuleFactory<T>
}
type PluginFactory = (...args: any) => Plugin
type BuiltinPlugins = typeof builtinPlugins
/**
* Utils that produce webpack `loader` objects
*/
interface ILoaderUtils {
json: LoaderResolver
yaml: LoaderResolver
null: LoaderResolver
raw: LoaderResolver
style: LoaderResolver
css: LoaderResolver
postcss: LoaderResolver<{
browsers?: Array<string>
overrideBrowserslist?: Array<string>
plugins?:
| Array<postcss.Plugin<any>>
| ((loader: Loader) => Array<postcss.Plugin<any>>)
}>
file: LoaderResolver
url: LoaderResolver
js: LoaderResolver
dependencies: LoaderResolver
miniCssExtract: LoaderResolver
imports: LoaderResolver
exports: LoaderResolver
eslint(schema: GraphQLSchema): Loader
}
interface IModuleThatUseGatsby {
name: string
path: string
}
type CssLoaderModuleOption = boolean | Record<string, any> | string
/**
* Utils that produce webpack rule objects
*/
interface IRuleUtils {
/**
* Handles JavaScript compilation via babel
*/
js: RuleFactory<{ modulesThatUseGatsby?: Array<IModuleThatUseGatsby> }>
dependencies: RuleFactory<{
modulesThatUseGatsby?: Array<IModuleThatUseGatsby>
}>
yaml: RuleFactory
fonts: RuleFactory
images: RuleFactory
miscAssets: RuleFactory
media: RuleFactory
css: ContextualRuleFactory<{
browsers?: Array<string>
modules?: CssLoaderModuleOption
}>
cssModules: RuleFactory
postcss: ContextualRuleFactory<{ overrideBrowserOptions: Array<string> }>
eslint: (schema: GraphQLSchema) => RuleSetRule
}
type PluginUtils = BuiltinPlugins & {
extractText: PluginFactory
uglify: PluginFactory
moment: PluginFactory
extractStats: PluginFactory
minifyJs: PluginFactory
minifyCss: PluginFactory
fastRefresh: PluginFactory
eslintGraphqlSchemaReload: PluginFactory
virtualModules: PluginFactory
}
/**
* webpack atoms namespace
*/
interface IWebpackUtils {
loaders: ILoaderUtils
rules: IRuleUtils
plugins: PluginUtils
}
/**
* A factory method that produces an atoms namespace
*/
export const createWebpackUtils = (
stage: Stage,
program: IProgram
): IWebpackUtils => {
const assetRelativeRoot = `static/`
const vendorRegex = /(node_modules|bower_components)/
const supportedBrowsers = getBrowsersList(program.directory)
const PRODUCTION = !stage.includes(`develop`)
const isSSR = stage.includes(`html`)
const jsxRuntimeExists = reactHasJsxRuntime()
const makeExternalOnly = (original: RuleFactory) => (
options = {}
): RuleSetRule => {
const rule = original(options)
rule.include = vendorRegex
return rule
}
const makeInternalOnly = (original: RuleFactory) => (
options = {}
): RuleSetRule => {
const rule = original(options)
rule.exclude = vendorRegex
return rule
}
let ident = 0
const loaders: ILoaderUtils = {
json: (options = {}) => {
return {
options,
loader: require.resolve(`json-loader`),
}
},
yaml: (options = {}) => {
return {
options,
loader: require.resolve(`yaml-loader`),
}
},
null: (options = {}) => {
return {
options,
loader: require.resolve(`null-loader`),
}
},
raw: (options = {}) => {
return {
options,
loader: require.resolve(`raw-loader`),
}
},
style: (options = {}) => {
return {
options,
loader: require.resolve(`style-loader`),
}
},
miniCssExtract: (options = {}) => {
return {
options,
// use MiniCssExtractPlugin only on production builds
loader: PRODUCTION
? MiniCssExtractPlugin.loader
: require.resolve(`style-loader`),
}
},
css: (options = {}) => {
return {
loader: isSSR
? require.resolve(`css-loader/locals`)
: require.resolve(`css-loader`),
options: {
sourceMap: !PRODUCTION,
camelCase: `dashesOnly`,
// https://github.com/webpack-contrib/css-loader/issues/406
localIdentName: `[name]--[local]--[hash:base64:5]`,
...options,
},
}
},
postcss: (options = {}) => {
let {
plugins,
overrideBrowserslist = supportedBrowsers,
...postcssOpts
} = options
return {
loader: require.resolve(`postcss-loader`),
options: {
ident: `postcss-${++ident}`,
sourceMap: !PRODUCTION,
plugins: (loader: Loader): Array<postcss.Plugin<any>> => {
plugins =
(typeof plugins === `function` ? plugins(loader) : plugins) || []
const autoprefixerPlugin = autoprefixer({
overrideBrowserslist,
flexbox: `no-2009`,
...((plugins.find(
plugin => plugin.postcssPlugin === `autoprefixer`
) as autoprefixer.Autoprefixer)?.options ?? {}),
})
return [flexbugs, autoprefixerPlugin, ...plugins]
},
...postcssOpts,
},
}
},
file: (options = {}) => {
return {
loader: require.resolve(`file-loader`),
options: {
name: `${assetRelativeRoot}[name]-[hash].[ext]`,
...options,
},
}
},
url: (options = {}) => {
return {
loader: require.resolve(`url-loader`),
options: {
limit: 10000,
name: `${assetRelativeRoot}[name]-[hash].[ext]`,
fallback: require.resolve(`file-loader`),
...options,
},
}
},
js: options => {
return {
options: {
stage,
reactRuntime: jsxRuntimeExists ? `automatic` : `classic`,
cacheDirectory: path.join(
program.directory,
`.cache`,
`webpack`,
`babel`
),
...options,
rootDir: program.directory,
},
loader: require.resolve(`./babel-loader`),
}
},
dependencies: options => {
return {
options: {
cacheDirectory: path.join(
program.directory,
`.cache`,
`webpack`,
`babel`
),
...options,
},
loader: require.resolve(`babel-loader`),
}
},
eslint: (schema: GraphQLSchema) => {
const options = eslintConfig(schema, jsxRuntimeExists)
return {
options,
loader: require.resolve(`eslint-loader`),
}
},
imports: (options = {}) => {
return {
options,
loader: require.resolve(`imports-loader`),
}
},
exports: (options = {}) => {
return {
options,
loader: require.resolve(`exports-loader`),
}
},
}
/**
* Rules
*/
const rules = {} as IRuleUtils
/**
* JavaScript loader via babel, includes userland code
* and packages that depend on `gatsby`
*/
{
const js = ({
modulesThatUseGatsby = [],
...options
}: {
modulesThatUseGatsby?: Array<IModuleThatUseGatsby>
} = {}): RuleSetRule => {
return {
test: /\.(js|mjs|jsx)$/,
include: (modulePath: string): boolean => {
// when it's not coming from node_modules we treat it as a source file.
if (!vendorRegex.test(modulePath)) {
return true
}
// If the module uses Gatsby as a dependency
// we want to treat it as src so we can extract queries
return modulesThatUseGatsby.some(module =>
modulePath.includes(module.path)
)
},
type: `javascript/auto`,
use: [
loaders.js({
...options,
configFile: true,
compact: PRODUCTION,
}),
],
}
}
rules.js = js
}
/**
* Node_modules JavaScript loader via babel
* Excludes core-js & babel-runtime to speedup babel transpilation
* Excludes modules that use Gatsby since the `rules.js` already transpiles those
*/
{
const dependencies = ({
modulesThatUseGatsby = [],
}: {
modulesThatUseGatsby?: Array<IModuleThatUseGatsby>
} = {}): RuleSetRule => {
const jsOptions = {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve(`babel-preset-gatsby/dependencies`),
{
stage,
},
],
],
// If an error happens in a package, it's possible to be
// because it was compiled. Thus, we don't want the browser
// debugger to show the original code. Instead, the code
// being evaluated would be much more helpful.
sourceMaps: false,
cacheIdentifier: JSON.stringify({
browerslist: supportedBrowsers,
gatsbyPreset: require(`babel-preset-gatsby/package.json`).version,
}),
}
// TODO REMOVE IN V3
// a list of vendors we know we shouldn't polyfill (we should have set core-js to entry but we didn't so we have to do this)
const VENDORS_TO_NOT_POLYFILL = [
`@babel[\\\\/]runtime`,
`@mikaelkristiansson[\\\\/]domready`,
`@reach[\\\\/]router`,
`babel-preset-gatsby`,
`core-js`,
`dom-helpers`,
`gatsby-legacy-polyfills`,
`gatsby-link`,
`gatsby-react-router-scroll`,
`invariant`,
`lodash`,
`mitt`,
`prop-types`,
`react-dom`,
`react`,
`regenerator-runtime`,
`scheduler`,
`scroll-behavior`,
`shallow-compare`,
`warning`,
`webpack`,
]
const doNotPolyfillRegex = new RegExp(
`[\\\\/]node_modules[\\\\/](${VENDORS_TO_NOT_POLYFILL.join(
`|`
)})[\\\\/]`
)
return {
test: /\.(js|mjs)$/,
exclude: (modulePath: string): boolean => {
// If dep is user land code, exclude
if (!vendorRegex.test(modulePath)) {
return true
}
// If dep uses Gatsby, exclude
if (
modulesThatUseGatsby.some(module =>
modulePath.includes(module.path)
)
) {
return true
}
return doNotPolyfillRegex.test(modulePath)
},
type: `javascript/auto`,
use: [loaders.dependencies(jsOptions)],
}
}
rules.dependencies = dependencies
}
rules.eslint = (schema: GraphQLSchema): RuleSetRule => {
return {
enforce: `pre`,
test: /\.jsx?$/,
exclude: (modulePath: string): boolean =>
modulePath.includes(VIRTUAL_MODULES_BASE_PATH) ||
vendorRegex.test(modulePath),
use: [loaders.eslint(schema)],
}
}
rules.yaml = (): RuleSetRule => {
return {
test: /\.ya?ml$/,
use: [loaders.json(), loaders.yaml()],
}
}
/**
* Font loader
*/
rules.fonts = (): RuleSetRule => {
return {
use: [loaders.url()],
test: /\.(eot|otf|ttf|woff(2)?)(\?.*)?$/,
}
}
/**
* Loads image assets, inlines images via a data URI if they are below
* the size threshold
*/
rules.images = (): RuleSetRule => {
return {
use: [loaders.url()],
test: /\.(ico|svg|jpg|jpeg|png|gif|webp|avif)(\?.*)?$/,
}
}
/**
* Loads audio and video and inlines them via a data URI if they are below
* the size threshold
*/
rules.media = (): RuleSetRule => {
return {
use: [loaders.url()],
test: /\.(mp4|webm|ogv|wav|mp3|m4a|aac|oga|flac)$/,
}
}
/**
* Loads assets without inlining
*/
rules.miscAssets = (): RuleSetRule => {
return {
use: [loaders.file()],
test: /\.pdf$/,
}
}
/**
* CSS style loader.
*/
{
const css: IRuleUtils["css"] = (options = {}): RuleSetRule => {
const { browsers, ...restOptions } = options
const use = [
loaders.css({ ...restOptions, importLoaders: 1 }),
loaders.postcss({ browsers }),
]
if (!isSSR)
use.unshift(
loaders.miniCssExtract({ hmr: !PRODUCTION && !restOptions.modules })
)
return {
use,
test: /\.css$/,
}
}
/**
* CSS style loader, _excludes_ node_modules.
*/
css.internal = makeInternalOnly(css)
css.external = makeExternalOnly(css)
const cssModules: IRuleUtils["cssModules"] = (options): RuleSetRule => {
const rule = css({ ...options, modules: true })
delete rule.exclude
rule.test = /\.module\.css$/
return rule
}
rules.css = css
rules.cssModules = cssModules
}
/**
* PostCSS loader.
*/
{
const postcss: ContextualRuleFactory = (options): RuleSetRule => {
return {
test: /\.css$/,
use: [loaders.css({ importLoaders: 1 }), loaders.postcss(options)],
}
}
/**
* PostCSS loader, _excludes_ node_modules.
*/
postcss.internal = makeInternalOnly(postcss)
postcss.external = makeExternalOnly(postcss)
rules.postcss = postcss
}
/**
* cast rules to IRuleUtils
*/
/**
* Plugins
*/
const plugins = { ...builtinPlugins } as PluginUtils
plugins.minifyJs = ({
terserOptions,
...options
}: { terserOptions?: TerserPlugin.TerserPluginOptions } = {}): Plugin =>
new TerserPlugin({
// TODO add proper cache keys
cache: path.join(program.directory, `.cache`, `webpack`, `terser`),
exclude: /\.min\.js/,
sourceMap: true,
terserOptions: {
ie8: false,
mangle: {
safari10: true,
},
parse: {
ecma: 8,
},
compress: {
ecma: 5,
},
output: {
ecma: 5,
},
...terserOptions,
},
...options,
})
plugins.minifyCss = (
options = {
cssProcessorPluginOptions: {
preset: [
`default`,
{
svgo: {
full: true,
plugins: [
{
// potentially destructive plugins removed - see https://github.com/gatsbyjs/gatsby/issues/15629
// convertShapeToPath: true,
// removeViewBox: true,
removeUselessDefs: true,
addAttributesToSVGElement: true,
addClassesToSVGElement: true,
cleanupAttrs: true,
cleanupEnableBackground: true,
cleanupIDs: true,
cleanupListOfValues: true,
cleanupNumericValues: true,
collapseGroups: true,
convertColors: true,
convertPathData: true,
convertStyleToAttrs: true,
convertTransform: true,
inlineStyles: true,
mergePaths: true,
minifyStyles: true,
moveElemsAttrsToGroup: true,
moveGroupAttrsToElems: true,
prefixIds: true,
removeAttributesBySelector: true,
removeAttrs: true,
removeComments: true,
removeDesc: true,
removeDimensions: true,
removeDoctype: true,
removeEditorsNSData: true,
removeElementsByAttr: true,
removeEmptyAttrs: true,
removeEmptyContainers: true,
removeEmptyText: true,
removeHiddenElems: true,
removeMetadata: true,
removeNonInheritableGroupAttrs: true,
removeOffCanvasPaths: true,
removeRasterImages: true,
removeScriptElement: true,
removeStyleElement: true,
removeTitle: true,
removeUnknownsAndDefaults: true,
removeUnusedNS: true,
removeUselessStrokeAndFill: true,
removeXMLNS: true,
removeXMLProcInst: true,
reusePaths: true,
sortAttrs: true,
},
],
},
},
],
},
}
): OptimizeCssAssetsPlugin => new OptimizeCssAssetsPlugin(options)
plugins.fastRefresh = (): Plugin =>
new ReactRefreshWebpackPlugin({
overlay: false,
})
plugins.extractText = (options: any): Plugin =>
new MiniCssExtractPlugin({
filename: `[name].[contenthash].css`,
chunkFilename: `[name].[contenthash].css`,
...options,
})
plugins.moment = (): Plugin => plugins.ignore(/^\.\/locale$/, /moment$/)
plugins.extractStats = (): GatsbyWebpackStatsExtractor =>
new GatsbyWebpackStatsExtractor()
plugins.eslintGraphqlSchemaReload = (): GatsbyWebpackEslintGraphqlSchemaReload =>
new GatsbyWebpackEslintGraphqlSchemaReload()
plugins.virtualModules = (): GatsbyWebpackVirtualModules =>
new GatsbyWebpackVirtualModules()
return {
loaders,
rules,
plugins,
}
}
export function reactHasJsxRuntime(): boolean {
// We've got some complains about the ecosystem not being ready for automatic so we disable it by default.
// People can use a custom babelrc file to support it
// try {
// // React is shipping a new jsx runtime that is to be used with
// // an option on @babel/preset-react called `runtime: automatic`
// // Not every version of React has this jsx-runtime yet. Eventually,
// // it will be backported to older versions of react and this check
// // will become unnecessary.
// // for now we also do the semver check until react 17 is more widely used
// // const react = require(`react/package.json`)
// // return (
// // !!require.resolve(`react/jsx-runtime.js`) &&
// // semver.major(react.version) >= 17
// // )
// } catch (e) {
// // If the require.resolve throws, that means this version of React
// // does not support the jsx runtime.
// }
return false
}