-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathwebpack-utils.ts
816 lines (736 loc) · 21.2 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
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
import * as path from "path"
import { RuleSetRule, WebpackPluginInstance } from "webpack"
import { GraphQLSchema } from "graphql"
import { Plugin as PostCSSPlugin } from "postcss"
import autoprefixer from "autoprefixer"
import flexbugs from "postcss-flexbugs-fixes"
import TerserPlugin from "terser-webpack-plugin"
import type { MinifyOptions as TerserOptions } from "terser"
import MiniCssExtractPlugin from "mini-css-extract-plugin"
import CssMinimizerPlugin from "css-minimizer-webpack-plugin"
import ReactRefreshWebpackPlugin from "@pmmmwh/react-refresh-webpack-plugin"
import { getBrowsersList } from "./browserslist"
import ESLintPlugin from "eslint-webpack-plugin"
import { cpuCoreCount } from "gatsby-core-utils"
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, eslintRequiredConfig } from "./eslint-config"
import { store } from "../redux"
type Loader = string | { loader: string; options?: { [name: string]: any } }
type LoaderResolver<T = Record<string, unknown>> = (options?: T) => Loader
type LoaderOptions = Record<string, any>
type RuleFactory<T = Record<string, unknown>> = (
options?: T & LoaderOptions
) => RuleSetRule
type ContextualRuleFactory<T = Record<string, unknown>> = RuleFactory<T> & {
internal?: RuleFactory<T>
external?: RuleFactory<T>
}
type PluginFactory = (...args: any) => WebpackPluginInstance
type BuiltinPlugins = typeof builtinPlugins
type CSSModulesOptions =
| boolean
| string
| {
mode?:
| "local"
| "global"
| "pure"
| ((resourcePath: string) => "local" | "global" | "pure")
auto?: boolean
exportGlobals?: boolean
localIdentName?: string
localIdentContext?: string
localIdentHashPrefix?: string
namedExport?: boolean
exportLocalsConvention?:
| "asIs"
| "camelCaseOnly"
| "camelCase"
| "dashes"
| "dashesOnly"
exportOnlyLocals?: boolean
}
type MiniCSSExtractLoaderModuleOptions =
| undefined
| boolean
| {
namedExport?: boolean
}
/**
* Utils that produce webpack `loader` objects
*/
interface ILoaderUtils {
yaml: LoaderResolver
style: LoaderResolver
css: LoaderResolver<{
url?: boolean | ((url: string, resourcePath: string) => boolean)
import?:
| boolean
| ((url: string, media: string, resourcePath: string) => boolean)
modules?: CSSModulesOptions
sourceMap?: boolean
importLoaders?: number
esModule?: boolean
}>
postcss: LoaderResolver<{
browsers?: Array<string>
overrideBrowserslist?: Array<string>
plugins?: Array<PostCSSPlugin> | ((loader: Loader) => Array<PostCSSPlugin>)
}>
file: LoaderResolver
url: LoaderResolver
js: LoaderResolver
json: LoaderResolver
null: LoaderResolver
raw: LoaderResolver
dependencies: LoaderResolver
miniCssExtract: LoaderResolver
imports?: LoaderResolver
exports?: LoaderResolver
}
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
eslintRequired: () => RuleSetRule
}
type PluginUtils = BuiltinPlugins & {
extractText: PluginFactory
uglify: PluginFactory
moment: PluginFactory
extractStats: PluginFactory
minifyJs: PluginFactory
minifyCss: PluginFactory
fastRefresh: PluginFactory
eslintGraphqlSchemaReload: PluginFactory
virtualModules: PluginFactory
eslint: PluginFactory
eslintRequired: PluginFactory
}
/**
* webpack atoms namespace
*/
interface IWebpackUtils {
loaders: ILoaderUtils
rules: IRuleUtils
plugins: PluginUtils
}
const vendorRegex = /(node_modules|bower_components)/
/**
* A factory method that produces an atoms namespace
*/
export const createWebpackUtils = (
stage: Stage,
program: IProgram
): IWebpackUtils => {
const assetRelativeRoot = `static/`
const supportedBrowsers = getBrowsersList(program.directory)
const PRODUCTION = !stage.includes(`develop`)
const isSSR = stage.includes(`html`)
const { config } = store.getState()
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
}
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`),
}
},
// TODO(v5): Re-Apply https://github.com/gatsbyjs/gatsby/pull/33979 with breaking change in inline loader syntax
miniCssExtract: (
options: {
modules?: MiniCSSExtractLoaderModuleOptions
} = {}
) => {
let moduleOptions: MiniCSSExtractLoaderModuleOptions = undefined
const { modules, ...restOptions } = options
if (typeof modules === `boolean` && options.modules) {
moduleOptions = {
namedExport: true,
}
} else {
moduleOptions = modules
}
return {
loader: MiniCssExtractPlugin.loader,
options: {
modules: moduleOptions,
...restOptions,
},
}
},
css: (options = {}) => {
let modulesOptions: CSSModulesOptions = false
if (options.modules) {
modulesOptions = {
auto: undefined,
namedExport: true,
localIdentName: `[name]--[local]--[hash:base64:5]`,
exportLocalsConvention: `dashesOnly`,
exportOnlyLocals: isSSR,
}
if (typeof options.modules === `object`) {
modulesOptions = {
...modulesOptions,
...options.modules,
}
}
}
return {
loader: require.resolve(`css-loader`),
options: {
// Absolute urls (https or //) are not send to this function. Only resolvable paths absolute or relative ones.
url: function (url: string): boolean {
// When an url starts with /
if (url.startsWith(`/`)) {
return false
}
return true
},
sourceMap: !PRODUCTION,
modules: modulesOptions,
},
}
},
postcss: (options = {}) => {
const {
plugins,
overrideBrowserslist = supportedBrowsers,
...postcssOpts
} = options
return {
loader: require.resolve(`postcss-loader`),
options: {
execute: false,
sourceMap: !PRODUCTION,
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
postcssOptions: (loaderContext: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let postCSSPlugins: Array<PostCSSPlugin> = []
if (plugins) {
postCSSPlugins =
typeof plugins === `function` ? plugins(loaderContext) : plugins
}
const autoprefixerPlugin = autoprefixer({
overrideBrowserslist,
flexbox: `no-2009`,
...((
postCSSPlugins.find(
plugin => plugin.postcssPlugin === `autoprefixer`
) as unknown as autoprefixer.ExportedAPI
)?.options ?? {}),
})
postCSSPlugins.unshift(autoprefixerPlugin)
postCSSPlugins.unshift(flexbugs)
return {
plugins: postCSSPlugins,
...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: config.jsxRuntime,
reactImportSource: config.jsxImportSource,
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`),
}
},
}
/**
* 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.yaml = (): RuleSetRule => {
return {
test: /\.ya?ml$/,
type: `json`,
use: [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 = [
!isSSR && loaders.miniCssExtract(restOptions),
loaders.css({ ...restOptions, importLoaders: 1 }),
loaders.postcss({ browsers }),
].filter(Boolean) as RuleSetRule["use"]
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?: TerserOptions
} = {}): WebpackPluginInstance =>
new TerserPlugin({
exclude: /\.min\.js/,
terserOptions: {
ie8: false,
mangle: {
safari10: true,
},
parse: {
ecma: 5,
},
compress: {
ecma: 5,
},
output: {
ecma: 5,
},
...terserOptions,
},
parallel: Math.max(1, cpuCoreCount() - 1),
...options,
})
plugins.minifyCss = (
options = {
minimizerOptions: {
preset: [
`default`,
{
svgo: {
full: true,
plugins: [
// potentially destructive plugins removed - see https://github.com/gatsbyjs/gatsby/issues/15629
// use correct config format and remove plugins requiring specific params - see https://github.com/gatsbyjs/gatsby/issues/31619
// List of default plugins and their defaults: https://github.com/svg/svgo#built-in-plugins
// Last update 2021-08-17
`cleanupAttrs`,
`cleanupEnableBackground`,
`cleanupIDs`,
`cleanupListOfValues`, // Default: disabled
`cleanupNumericValues`,
`collapseGroups`,
`convertColors`,
`convertPathData`,
`convertStyleToAttrs`, // Default: disabled
`convertTransform`,
`inlineStyles`,
`mergePaths`,
`minifyStyles`,
`moveElemsAttrsToGroup`,
`moveGroupAttrsToElems`,
`prefixIds`, // Default: disabled
`removeComments`,
`removeDesc`,
`removeDoctype`,
`removeEditorsNSData`,
`removeEmptyAttrs`,
`removeEmptyContainers`,
`removeEmptyText`,
`removeHiddenElems`,
`removeMetadata`,
`removeNonInheritableGroupAttrs`,
`removeOffCanvasPaths`, // Default: disabled
`removeRasterImages`, // Default: disabled
`removeScriptElement`, // Default: disabled
`removeStyleElement`, // Default: disabled
`removeTitle`,
`removeUnknownsAndDefaults`,
`removeUnusedNS`,
`removeUselessDefs`,
`removeUselessStrokeAndFill`,
`removeXMLProcInst`,
`reusePaths`, // Default: disabled
`sortAttrs`, // Default: disabled
],
},
},
],
},
}
): CssMinimizerPlugin =>
new CssMinimizerPlugin({
parallel: Math.max(1, cpuCoreCount() - 1),
...options,
})
plugins.fastRefresh = ({ modulesThatUseGatsby }): WebpackPluginInstance => {
const regExpToHack = /node_modules/
regExpToHack.test = (modulePath: string): boolean => {
// when it's not coming from node_modules we treat it as a source file.
if (!vendorRegex.test(modulePath)) {
return false
}
// If the module uses Gatsby as a dependency
// we want to treat it as src because of shadowing
return !modulesThatUseGatsby.some(module =>
modulePath.includes(module.path)
)
}
return new ReactRefreshWebpackPlugin({
overlay: {
sockIntegration: `whm`,
module: path.join(__dirname, `fast-refresh-module`),
},
// this is a bit hacky - exclude expect string or regexp or array of those
// so this is tricking ReactRefreshWebpackPlugin with providing regexp with
// overwritten .test method
exclude: regExpToHack,
})
}
plugins.extractText = (options: any): WebpackPluginInstance =>
new MiniCssExtractPlugin({
...options,
})
plugins.moment = (): WebpackPluginInstance =>
plugins.ignore({ resourceRegExp: /^\.\/locale$/, contextRegExp: /moment$/ })
plugins.extractStats = (): GatsbyWebpackStatsExtractor =>
new GatsbyWebpackStatsExtractor()
plugins.eslintGraphqlSchemaReload =
(): GatsbyWebpackEslintGraphqlSchemaReload =>
new GatsbyWebpackEslintGraphqlSchemaReload()
plugins.virtualModules = (): GatsbyWebpackVirtualModules =>
new GatsbyWebpackVirtualModules()
plugins.eslint = (schema: GraphQLSchema): WebpackPluginInstance => {
const options = {
extensions: [`js`, `jsx`],
exclude: [
`/node_modules/`,
`/bower_components/`,
VIRTUAL_MODULES_BASE_PATH,
],
...eslintConfig(schema, config.jsxRuntime === `automatic`),
}
// @ts-ignore
return new ESLintPlugin(options)
}
plugins.eslintRequired = (): WebpackPluginInstance => {
const options = {
extensions: [`js`, `jsx`],
exclude: [
`/node_modules/`,
`/bower_components/`,
VIRTUAL_MODULES_BASE_PATH,
],
...eslintRequiredConfig,
}
// @ts-ignore
return new ESLintPlugin(options)
}
return {
loaders,
rules,
plugins,
}
}