/
index.ts
579 lines (547 loc) · 17.3 KB
/
index.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
import path from 'path'
import curry from 'next/dist/compiled/lodash.curry'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { loader, plugin } from '../../helpers'
import { ConfigurationContext, ConfigurationFn, pipe } from '../../utils'
import { getCssModuleLoader, getGlobalCssLoader } from './loaders'
import { getNextFontLoader } from './loaders/next-font'
import {
getCustomDocumentError,
getGlobalImportError,
getGlobalModuleImportError,
getLocalModuleImportError,
} from './messages'
import { getPostCssPlugins } from './plugins'
import { nonNullable } from '../../../../../lib/non-nullable'
import { WEBPACK_LAYERS } from '../../../../../lib/constants'
// RegExps for all Style Sheet variants
export const regexLikeCss = /\.(css|scss|sass)$/
// RegExps for Style Sheets
const regexCssGlobal = /(?<!\.module)\.css$/
const regexCssModules = /\.module\.css$/
// RegExps for Syntactically Awesome Style Sheets
const regexSassGlobal = /(?<!\.module)\.(scss|sass)$/
const regexSassModules = /\.module\.(scss|sass)$/
/**
* Mark a rule as removable if built-in CSS support is disabled
*/
function markRemovable(r: webpack.RuleSetRule): webpack.RuleSetRule {
Object.defineProperty(r, Symbol.for('__next_css_remove'), {
enumerable: false,
value: true,
})
return r
}
let postcssInstancePromise: Promise<any>
export async function lazyPostCSS(
rootDirectory: string,
supportedBrowsers: string[] | undefined,
disablePostcssPresetEnv: boolean | undefined
) {
if (!postcssInstancePromise) {
postcssInstancePromise = (async () => {
const postcss = require('postcss')
// @ts-ignore backwards compat
postcss.plugin = function postcssPlugin(name, initializer) {
function creator(...args: any) {
let transformer = initializer(...args)
transformer.postcssPlugin = name
// transformer.postcssVersion = new Processor().version
return transformer
}
let cache: any
Object.defineProperty(creator, 'postcss', {
get() {
if (!cache) cache = creator()
return cache
},
})
creator.process = function (
css: any,
processOpts: any,
pluginOpts: any
) {
return postcss([creator(pluginOpts)]).process(css, processOpts)
}
return creator
}
// @ts-ignore backwards compat
postcss.vendor = {
/**
* Returns the vendor prefix extracted from an input string.
*
* @example
* postcss.vendor.prefix('-moz-tab-size') //=> '-moz-'
* postcss.vendor.prefix('tab-size') //=> ''
*/
prefix: function prefix(prop: string): string {
const match = prop.match(/^(-\w+-)/)
if (match) {
return match[0]
}
return ''
},
/**
* Returns the input string stripped of its vendor prefix.
*
* @example
* postcss.vendor.unprefixed('-moz-tab-size') //=> 'tab-size'
*/
unprefixed: function unprefixed(
/**
* String with or without vendor prefix.
*/
prop: string
): string {
return prop.replace(/^-\w+-/, '')
},
}
const postCssPlugins = await getPostCssPlugins(
rootDirectory,
supportedBrowsers,
disablePostcssPresetEnv
)
return {
postcss,
postcssWithPlugins: postcss(postCssPlugins),
}
})()
}
return postcssInstancePromise
}
export const css = curry(async function css(
ctx: ConfigurationContext,
config: webpack.Configuration
) {
const {
prependData: sassPrependData,
additionalData: sassAdditionalData,
...sassOptions
} = ctx.sassOptions
const lazyPostCSSInitializer = () =>
lazyPostCSS(
ctx.rootDirectory,
ctx.supportedBrowsers,
ctx.experimental.disablePostcssPresetEnv
)
const sassPreprocessors: webpack.RuleSetUseItem[] = [
// First, process files with `sass-loader`: this inlines content, and
// compiles away the proprietary syntax.
{
loader: require.resolve('next/dist/compiled/sass-loader'),
options: {
// Source maps are required so that `resolve-url-loader` can locate
// files original to their source directory.
sourceMap: true,
sassOptions,
additionalData: sassPrependData || sassAdditionalData,
},
},
// Then, `sass-loader` will have passed-through CSS imports as-is instead
// of inlining them. Because they were inlined, the paths are no longer
// correct.
// To fix this, we use `resolve-url-loader` to rewrite the CSS
// imports to real file paths.
{
loader: require.resolve('../../../loaders/resolve-url-loader/index'),
options: {
postcss: lazyPostCSSInitializer,
// Source maps are not required here, but we may as well emit
// them.
sourceMap: true,
},
},
]
const fns: ConfigurationFn[] = []
// Resolve the configured font loaders, the resolved files are noop files that next-font-loader will match
let fontLoaders: [string, string][] | undefined = ctx.experimental.fontLoaders
? ctx.experimental.fontLoaders.map(({ loader: fontLoader, options }) => [
path.join(require.resolve(fontLoader), '../target.css'),
options,
])
: undefined
fontLoaders?.forEach(([fontLoaderPath, fontLoaderOptions]) => {
// Matches the resolved font loaders noop files to run next-font-loader
fns.push(
loader({
oneOf: [
markRemovable({
sideEffects: false,
test: fontLoaderPath,
use: getNextFontLoader(
ctx,
lazyPostCSSInitializer,
fontLoaderOptions
),
}),
],
})
)
})
// CSS cannot be imported in _document. This comes before everything because
// global CSS nor CSS modules work in said file.
fns.push(
loader({
oneOf: [
markRemovable({
test: regexLikeCss,
// Use a loose regex so we don't have to crawl the file system to
// find the real file name (if present).
issuer: /pages[\\/]_document\./,
use: {
loader: 'error-loader',
options: {
reason: getCustomDocumentError(),
},
},
}),
],
})
)
const shouldIncludeExternalCSSImports =
!!ctx.experimental.craCompat || !!ctx.transpilePackages
// CSS modules & SASS modules support. They are allowed to be imported in anywhere.
fns.push(
// CSS Modules should never have side effects. This setting will
// allow unused CSS to be removed from the production build.
// We ensure this by disallowing `:global()` CSS at the top-level
// via the `pure` mode in `css-loader`.
loader({
oneOf: [
// For app dir, it has to match one of the 2 layers and then apply a
// specific loader.
ctx.hasAppDir && !ctx.isProduction
? markRemovable({
sideEffects: false,
test: regexCssModules,
issuerLayer: {
or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.client],
},
use: [
require.resolve('../../../loaders/next-flight-css-dev-loader'),
...getCssModuleLoader(ctx, lazyPostCSSInitializer),
],
})
: null,
ctx.hasAppDir && !ctx.isServer
? markRemovable({
sideEffects: false,
test: regexCssModules,
use: [
require.resolve('../../../loaders/next-flight-css-dev-loader'),
...getCssModuleLoader(ctx, lazyPostCSSInitializer),
],
})
: null,
markRemovable({
sideEffects: false,
test: regexCssModules,
use: getCssModuleLoader(ctx, lazyPostCSSInitializer),
}),
].filter(nonNullable),
}),
// Opt-in support for Sass (using .scss or .sass extensions).
// Sass Modules should never have side effects. This setting will
// allow unused Sass to be removed from the production build.
// We ensure this by disallowing `:global()` Sass at the top-level
// via the `pure` mode in `css-loader`.
loader({
oneOf: [
// For app dir, we match both server and client layers.
ctx.hasAppDir && !ctx.isProduction
? markRemovable({
sideEffects: false,
test: regexSassModules,
issuerLayer: {
or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.client],
},
use: [
require.resolve('../../../loaders/next-flight-css-dev-loader'),
...getCssModuleLoader(
ctx,
lazyPostCSSInitializer,
sassPreprocessors
),
],
})
: null,
ctx.hasAppDir && !ctx.isServer
? markRemovable({
sideEffects: false,
test: regexSassModules,
use: [
require.resolve('../../../loaders/next-flight-css-dev-loader'),
...getCssModuleLoader(
ctx,
lazyPostCSSInitializer,
sassPreprocessors
),
],
})
: null,
markRemovable({
sideEffects: false,
test: regexSassModules,
use: getCssModuleLoader(
ctx,
lazyPostCSSInitializer,
sassPreprocessors
),
}),
].filter(nonNullable),
}),
// Throw an error for CSS Modules used outside their supported scope
loader({
oneOf: [
markRemovable({
test: [regexCssModules, regexSassModules],
use: {
loader: 'error-loader',
options: {
reason: getLocalModuleImportError(),
},
},
}),
],
})
)
// Global CSS and SASS support.
if (ctx.isServer) {
fns.push(
loader({
oneOf: [
ctx.hasAppDir && !ctx.isProduction
? markRemovable({
sideEffects: true,
test: [regexCssGlobal, regexSassGlobal],
issuerLayer: {
or: [WEBPACK_LAYERS.server, WEBPACK_LAYERS.client],
},
use: require.resolve(
'../../../loaders/next-flight-css-dev-loader'
),
})
: null,
markRemovable({
// CSS imports have side effects, even on the server side.
sideEffects: true,
test: [regexCssGlobal, regexSassGlobal],
use: require.resolve('next/dist/compiled/ignore-loader'),
}),
].filter(nonNullable),
})
)
} else {
// They are allowed to be loaded when any of the following is true:
// - hasAppDir: If the issuerLayer is RSC
// - If the CSS file is located in `node_modules`
// - If the CSS file is located in another package in a monorepo (outside of the current rootDir)
// - If the issuer is pages/_app (matched later)
const allowedExternalCSSImports = {
and: [
{
or: [
/node_modules/,
{
not: [ctx.rootDirectory],
},
],
},
],
}
fns.push(
loader({
oneOf: [
ctx.hasAppDir
? markRemovable({
sideEffects: true,
test: regexCssGlobal,
use: [
require.resolve(
'../../../loaders/next-flight-css-dev-loader'
),
...getGlobalCssLoader(ctx, lazyPostCSSInitializer),
],
})
: null,
ctx.hasAppDir
? markRemovable({
sideEffects: true,
test: regexSassGlobal,
use: [
require.resolve(
'../../../loaders/next-flight-css-dev-loader'
),
...getGlobalCssLoader(
ctx,
lazyPostCSSInitializer,
sassPreprocessors
),
],
})
: null,
!ctx.hasAppDir
? markRemovable({
sideEffects: true,
test: regexCssGlobal,
include: allowedExternalCSSImports,
issuer: shouldIncludeExternalCSSImports
? undefined
: {
and: [ctx.rootDirectory],
not: [/node_modules/],
},
use: getGlobalCssLoader(ctx, lazyPostCSSInitializer),
})
: null,
!ctx.hasAppDir
? markRemovable({
sideEffects: true,
test: regexSassGlobal,
include: allowedExternalCSSImports,
issuer: shouldIncludeExternalCSSImports
? undefined
: {
and: [ctx.rootDirectory],
not: [/node_modules/],
},
use: getGlobalCssLoader(
ctx,
lazyPostCSSInitializer,
sassPreprocessors
),
})
: null,
].filter(nonNullable),
})
)
if (ctx.customAppFile) {
fns.push(
loader({
oneOf: [
markRemovable({
sideEffects: true,
test: regexCssGlobal,
issuer: { and: [ctx.customAppFile] },
use: getGlobalCssLoader(ctx, lazyPostCSSInitializer),
}),
],
}),
loader({
oneOf: [
markRemovable({
sideEffects: true,
test: regexSassGlobal,
issuer: { and: [ctx.customAppFile] },
use: getGlobalCssLoader(
ctx,
lazyPostCSSInitializer,
sassPreprocessors
),
}),
],
})
)
}
}
// Throw an error for Global CSS used inside of `node_modules`
if (!shouldIncludeExternalCSSImports) {
fns.push(
loader({
oneOf: [
markRemovable({
test: [regexCssGlobal, regexSassGlobal],
issuer: { and: [/node_modules/] },
use: {
loader: 'error-loader',
options: {
reason: getGlobalModuleImportError(),
},
},
}),
],
})
)
}
// Throw an error for Global CSS used outside of our custom <App> file
fns.push(
loader({
oneOf: [
markRemovable({
test: [regexCssGlobal, regexSassGlobal],
issuer: ctx.hasAppDir
? {
// If it's inside the app dir, but not importing from a layout file,
// throw an error.
and: [ctx.rootDirectory],
not: [/layout\.(js|mjs|jsx|ts|tsx)$/],
}
: undefined,
use: {
loader: 'error-loader',
options: {
reason: getGlobalImportError(),
},
},
}),
],
})
)
if (ctx.isClient) {
// Automatically transform references to files (i.e. url()) into URLs
// e.g. url(./logo.svg)
fns.push(
loader({
oneOf: [
markRemovable({
// This should only be applied to CSS files
issuer: regexLikeCss,
// Exclude extensions that webpack handles by default
exclude: [
/\.(js|mjs|jsx|ts|tsx)$/,
/\.html$/,
/\.json$/,
/\.webpack\[[^\]]+\]$/,
],
// `asset/resource` always emits a URL reference, where `asset`
// might inline the asset as a data URI
type: 'asset/resource',
}),
],
})
)
}
// Enable full mini-css-extract-plugin hmr for prod mode pages or app dir
if (ctx.isClient && (ctx.isProduction || ctx.hasAppDir)) {
// Extract CSS as CSS file(s) in the client-side production bundle.
const MiniCssExtractPlugin =
require('../../../plugins/mini-css-extract-plugin').default
fns.push(
plugin(
// @ts-ignore webpack 5 compat
new MiniCssExtractPlugin({
filename: ctx.isProduction
? 'static/css/[contenthash].css'
: 'static/css/[name].css',
chunkFilename: ctx.isProduction
? 'static/css/[contenthash].css'
: 'static/css/[name].css',
// Next.js guarantees that CSS order "doesn't matter", due to imposed
// restrictions:
// 1. Global CSS can only be defined in a single entrypoint (_app)
// 2. CSS Modules generate scoped class names by default and cannot
// include Global CSS (:global() selector).
//
// While not a perfect guarantee (e.g. liberal use of `:global()`
// selector), this assumption is required to code-split CSS.
//
// If this warning were to trigger, it'd be unactionable by the user,
// but likely not valid -- so we disable it.
ignoreOrder: true,
})
)
)
}
const fn = pipe(...fns)
return fn(config)
})