forked from tailwindlabs/tailwindcss.com
-
Notifications
You must be signed in to change notification settings - Fork 3
/
next.config.js
429 lines (391 loc) · 13.6 KB
/
next.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
const path = require('path')
const { createLoader } = require('simple-functional-loader')
const frontMatter = require('front-matter')
const withSmartQuotes = require('@silvenon/remark-smartypants')
const { withTableOfContents } = require('./remark/withTableOfContents')
const { withSyntaxHighlighting } = require('./remark/withSyntaxHighlighting')
const { withNextLinks } = require('./remark/withNextLinks')
const { withLinkRoles } = require('./rehype/withLinkRoles')
const minimatch = require('minimatch')
const withExamples = require('./remark/withExamples')
const {
highlightCode,
fixSelectorEscapeTokens,
simplifyToken,
normalizeTokens,
} = require('./remark/utils')
const { withPrevalInstructions } = require('./remark/withPrevalInstructions')
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
const defaultConfig = require('tailwindcss/resolveConfig')(require('tailwindcss/defaultConfig'))
const dlv = require('dlv')
const Prism = require('prismjs')
const fallbackLayouts = {
'src/pages/docs/**/*': ['@/layouts/DocumentationLayout', 'DocumentationLayout'],
}
const fallbackDefaultExports = {
'src/pages/{docs,components}/**/*': ['@/layouts/ContentsLayout', 'ContentsLayout'],
'src/pages/blog/**/*': ['@/layouts/BlogPostLayout', 'BlogPostLayout'],
}
const fallbackGetStaticProps = {
'src/pages/blog/**/*': '@/layouts/BlogPostLayout',
}
module.exports = withBundleAnalyzer({
swcMinify: true,
pageExtensions: ['js', 'jsx', 'mdx'],
experimental: {
esmExternals: false,
},
async redirects() {
return require('./redirects.json')
},
webpack(config, options) {
config.module.rules.push({
test: /\.mp4$/i,
issuer: /\.(jsx?|tsx?|mdx)$/,
use: [
{
loader: 'file-loader',
options: {
publicPath: '/_next',
name: 'static/media/[name].[hash].[ext]',
},
},
],
})
config.resolve.alias['defaultConfig$'] = require.resolve('tailwindcss/defaultConfig')
config.module.rules.push({
test: require.resolve('tailwindcss/defaultConfig'),
use: createLoader(function (_source) {
return `export default ${JSON.stringify(defaultConfig)}`
}),
})
config.resolve.alias['utilities$'] = require.resolve('tailwindcss/lib/corePlugins.js')
// import utilities from 'utilities?plugin=backgroundColor'
config.module.rules.push({
resourceQuery: /plugin/,
test: require.resolve('tailwindcss/lib/corePlugins.js'),
use: createLoader(function (_source) {
let pluginName = new URLSearchParams(this.resourceQuery).get('plugin')
let plugin = require('tailwindcss/lib/corePlugins.js').corePlugins[pluginName]
return `export default ${JSON.stringify(getUtilities(plugin))}`
}),
})
config.module.rules.push({
resourceQuery: /examples/,
test: require.resolve('tailwindcss/lib/corePlugins.js'),
use: createLoader(function (_source) {
let plugins = require('tailwindcss/lib/corePlugins.js').corePlugins
let examples = Object.entries(plugins).map(([name, plugin]) => {
let utilities = getUtilities(plugin)
return {
plugin: name,
example:
Object.keys(utilities).length > 0
? Object.keys(utilities)
[Math.floor((Object.keys(utilities).length - 1) / 2)].split(/[>:]/)[0]
.trim()
.substr(1)
.replace(/\\/g, '')
: undefined,
}
})
return `export default ${JSON.stringify(examples)}`
}),
})
config.module.rules.push({
test: /\.svg$/,
use: [
{ loader: '@svgr/webpack', options: { svgoConfig: { plugins: { removeViewBox: false } } } },
{
loader: 'file-loader',
options: {
publicPath: '/_next',
name: 'static/media/[name].[hash].[ext]',
},
},
],
})
// Remove the 3px deadzone for drag gestures in Framer Motion
config.module.rules.push({
test: /node_modules\/framer-motion/,
use: createLoader(function (source) {
return source.replace(
/var isDistancePastThreshold = .*?$/m,
'var isDistancePastThreshold = true'
)
}),
})
config.module.rules.push({
resourceQuery: /fields/,
use: createLoader(function (source) {
let fields = new URLSearchParams(this.resourceQuery).get('fields').split(',')
return JSON.stringify(JSON.parse(source), (key, value) => {
return ['', ...fields].includes(key) ? value : undefined
})
}),
})
config.module.rules.push({
resourceQuery: /highlight/,
use: [
options.defaultLoaders.babel,
createLoader(function (source) {
let lang =
new URLSearchParams(this.resourceQuery).get('highlight') ||
this.resourcePath.split('.').pop()
let isDiff = lang.startsWith('diff-')
let prismLang = isDiff ? lang.substr(5) : lang
let grammar = Prism.languages[isDiff ? 'diff' : prismLang]
let tokens = Prism.tokenize(source, grammar, lang)
if (lang === 'css') {
fixSelectorEscapeTokens(tokens)
}
return `
export const tokens = ${JSON.stringify(tokens.map(simplifyToken))}
export const lines = ${JSON.stringify(normalizeTokens(tokens))}
export const code = ${JSON.stringify(source)}
export const highlightedCode = ${JSON.stringify(highlightCode(source, lang))}
`
}),
],
})
let mdx = (plugins = []) => [
{
loader: '@mdx-js/loader',
options: {
remarkPlugins: [
withPrevalInstructions,
withExamples,
withTableOfContents,
withSyntaxHighlighting,
withNextLinks,
withSmartQuotes,
...plugins,
],
rehypePlugins: [withLinkRoles],
},
},
createLoader(function (source) {
let pathSegments = this.resourcePath.split(path.sep)
let slug =
pathSegments[pathSegments.length - 1] === 'index.mdx'
? pathSegments[pathSegments.length - 2]
: pathSegments[pathSegments.length - 1].replace(/\.mdx$/, '')
return source + `\n\nexport const slug = '${slug}'`
}),
]
config.module.rules.push({
test: { and: [/\.mdx$/, /snippets/] },
resourceQuery: { not: [/rss/, /preview/] },
use: [
options.defaultLoaders.babel,
{
loader: '@mdx-js/loader',
options: {
remarkPlugins: [withSyntaxHighlighting],
},
},
],
})
config.module.rules.push({
test: /\.mdx$/,
resourceQuery: /rss/,
use: [options.defaultLoaders.babel, ...mdx()],
})
config.module.rules.push({
test: /\.mdx$/,
resourceQuery: /preview/,
use: [
options.defaultLoaders.babel,
createLoader(function (src) {
const [preview] = src.split('<!--/excerpt-->')
return preview.replace('<!--excerpt-->', '')
}),
...mdx([
() => (tree) => {
let firstParagraphIndex = tree.children.findIndex((child) => child.type === 'paragraph')
if (firstParagraphIndex > -1) {
tree.children = tree.children.filter((child, index) => {
if (child.type === 'import' || child.type === 'export') {
return true
}
return index <= firstParagraphIndex
})
}
},
]),
],
})
config.module.rules.push({
test: { and: [/\.mdx$/], not: [/snippets/] },
resourceQuery: { not: [/rss/, /preview/] },
use: [
options.defaultLoaders.babel,
createLoader(function (source) {
if (source.includes('/*START_META*/')) {
const [meta] = source.match(/\/\*START_META\*\/(.*?)\/\*END_META\*\//s)
return 'export default ' + meta
}
return (
source.replace(/export const/gs, 'const') + `\nMDXContent.layoutProps = layoutProps\n`
)
}),
...mdx(),
createLoader(function (source) {
let fields = new URLSearchParams(this.resourceQuery.substr(1)).get('meta') ?? undefined
let { attributes: meta, body } = frontMatter(source)
if (fields) {
for (let field in meta) {
if (!fields.split(',').includes(field)) {
delete meta[field]
}
}
}
let extra = []
let resourcePath = path.relative(__dirname, this.resourcePath)
if (!/^\s*export\s+(var|let|const)\s+Layout\s+=/m.test(source)) {
for (let glob in fallbackLayouts) {
if (minimatch(resourcePath, glob)) {
extra.push(
`import { ${fallbackLayouts[glob][1]} as _Layout } from '${fallbackLayouts[glob][0]}'`,
'export const Layout = _Layout'
)
break
}
}
}
if (!/^\s*export\s+default\s+/m.test(source.replace(/```(.*?)```/gs, ''))) {
for (let glob in fallbackDefaultExports) {
if (minimatch(resourcePath, glob)) {
extra.push(
`import { ${fallbackDefaultExports[glob][1]} as _Default } from '${fallbackDefaultExports[glob][0]}'`,
'export default _Default'
)
break
}
}
}
if (
!/^\s*export\s+(async\s+)?function\s+getStaticProps\s+/m.test(
source.replace(/```(.*?)```/gs, '')
)
) {
for (let glob in fallbackGetStaticProps) {
if (minimatch(resourcePath, glob)) {
extra.push(`export { getStaticProps } from '${fallbackGetStaticProps[glob]}'`)
break
}
}
}
let metaExport
if (!/export\s+(const|let|var)\s+meta\s*=/.test(source)) {
metaExport =
typeof fields === 'undefined'
? `export const meta = ${JSON.stringify(meta)}`
: `export const meta = /*START_META*/${JSON.stringify(meta || {})}/*END_META*/`
}
return [
...(typeof fields === 'undefined' ? extra : []),
typeof fields === 'undefined'
? body.replace(/<!--excerpt-->.*<!--\/excerpt-->/s, '')
: '',
metaExport,
]
.filter(Boolean)
.join('\n\n')
}),
],
})
config.module.rules.push(...require('./translate')())
return config
},
})
function normalizeProperties(input) {
if (typeof input !== 'object') return input
if (Array.isArray(input)) return input.map(normalizeProperties)
return Object.keys(input).reduce((newObj, key) => {
let val = input[key]
let newVal = typeof val === 'object' ? normalizeProperties(val) : val
newObj[key.replace(/([a-z])([A-Z])/g, (m, p1, p2) => `${p1}-${p2.toLowerCase()}`)] = newVal
return newObj
}, {})
}
function getUtilities(plugin, { includeNegativeValues = false } = {}) {
if (!plugin) return {}
const utilities = {}
function addUtilities(utils) {
utils = Array.isArray(utils) ? utils : [utils]
for (let i = 0; i < utils.length; i++) {
for (let prop in utils[i]) {
for (let p in utils[i][prop]) {
if (p.startsWith('@defaults')) {
delete utils[i][prop][p]
}
}
utilities[prop] = normalizeProperties(utils[i][prop])
}
}
}
plugin({
addBase: () => {},
addDefaults: () => {},
addComponents: () => {},
corePlugins: () => true,
prefix: (x) => x,
config: (option, defaultValue) => (option ? defaultValue : { future: {} }),
addUtilities,
theme: (key, defaultValue) => dlv(defaultConfig.theme, key, defaultValue),
matchUtilities: (matches, { values, supportsNegativeValues } = {}) => {
if (!values) return
let modifierValues = Object.entries(values)
if (includeNegativeValues && supportsNegativeValues) {
let negativeValues = []
for (let [key, value] of modifierValues) {
let negatedValue = require('tailwindcss/lib/util/negateValue').default(value)
if (negatedValue) {
negativeValues.push([`-${key}`, negatedValue])
}
}
modifierValues.push(...negativeValues)
}
let result = Object.entries(matches).flatMap(([name, utilityFunction]) => {
return modifierValues
.map(([modifier, value]) => {
let declarations = utilityFunction(value, {
includeRules(rules) {
addUtilities(rules)
},
})
if (!declarations) {
return null
}
return {
[require('tailwindcss/lib/util/nameClass').default(name, modifier)]: declarations,
}
})
.filter(Boolean)
})
for (let obj of result) {
for (let key in obj) {
let deleteKey = false
for (let subkey in obj[key]) {
if (subkey.startsWith('@defaults')) {
delete obj[key][subkey]
continue
}
if (subkey.includes('&')) {
result.push({
[subkey.replace(/&/g, key)]: obj[key][subkey],
})
deleteKey = true
}
}
if (deleteKey) delete obj[key]
}
}
addUtilities(result)
},
})
return utilities
}