Commit 8247f19f authored by Joe Haddad's avatar Joe Haddad Committed by JJ Kasper

Defer Loading CSS Configuration (#9889)

parent b0892eff
...@@ -28,6 +28,7 @@ import { ...@@ -28,6 +28,7 @@ import {
VALID_MIDDLEWARE, VALID_MIDDLEWARE,
} from './plugins/collect-plugins' } from './plugins/collect-plugins'
import { build as buildConfiguration } from './webpack/config' import { build as buildConfiguration } from './webpack/config'
import { __overrideCssConfiguration } from './webpack/config/blocks/css'
// @ts-ignore: JS file // @ts-ignore: JS file
import { pluginLoaderOptions } from './webpack/loaders/next-plugin-loader' import { pluginLoaderOptions } from './webpack/loaders/next-plugin-loader'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin' import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
...@@ -946,6 +947,8 @@ export default async function getBaseWebpackConfig( ...@@ -946,6 +947,8 @@ export default async function getBaseWebpackConfig(
e => (e as any).__next_css_remove !== true e => (e as any).__next_css_remove !== true
) )
} }
} else {
await __overrideCssConfiguration(dir, webpackConfig)
} }
} }
......
import curry from 'lodash.curry' import curry from 'lodash.curry'
import path from 'path' import path from 'path'
import webpack, { Configuration } from 'webpack' import webpack, { Configuration, RuleSetRule } from 'webpack'
import MiniCssExtractPlugin from '../../../plugins/mini-css-extract-plugin' import MiniCssExtractPlugin from '../../../plugins/mini-css-extract-plugin'
import { loader } from '../../helpers' import { loader } from '../../helpers'
import { ConfigurationContext, ConfigurationFn, pipe } from '../../utils' import { ConfigurationContext, ConfigurationFn, pipe } from '../../utils'
...@@ -66,6 +66,37 @@ function getClientStyleLoader({ ...@@ -66,6 +66,37 @@ function getClientStyleLoader({
} }
} }
export async function __overrideCssConfiguration(
rootDirectory: string,
config: Configuration
) {
const postCssPlugins = await getPostCssPlugins(rootDirectory)
function patch(rule: RuleSetRule) {
if (
rule.options &&
typeof rule.options === 'object' &&
rule.options['ident'] === '__nextjs_postcss'
) {
rule.options.plugins = postCssPlugins
} else if (Array.isArray(rule.oneOf)) {
rule.oneOf.forEach(patch)
} else if (Array.isArray(rule.use)) {
rule.use.forEach(u => {
if (typeof u === 'object') {
patch(u)
}
})
}
}
// TODO: remove this rule, ESLint bug
// eslint-disable-next-line no-unused-expressions
config.module?.rules?.forEach(entry => {
patch(entry)
})
}
export const css = curry(async function css( export const css = curry(async function css(
enabled: boolean, enabled: boolean,
ctx: ConfigurationContext, ctx: ConfigurationContext,
...@@ -88,7 +119,13 @@ export const css = curry(async function css( ...@@ -88,7 +119,13 @@ export const css = curry(async function css(
}), }),
] ]
const postCssPlugins = await getPostCssPlugins(ctx.rootDirectory) const postCssPlugins = await getPostCssPlugins(
ctx.rootDirectory,
// TODO: In the future, we should stop supporting old CSS setups and
// unconditionally inject ours. When that happens, we should remove this
// function argument.
true
)
// CSS Modules support must be enabled on the server and client so the class // CSS Modules support must be enabled on the server and client so the class
// names are availble for SSR or Prerendering. // names are availble for SSR or Prerendering.
fns.push( fns.push(
...@@ -140,7 +177,7 @@ export const css = curry(async function css( ...@@ -140,7 +177,7 @@ export const css = curry(async function css(
{ {
loader: require.resolve('postcss-loader'), loader: require.resolve('postcss-loader'),
options: { options: {
ident: 'postcss', ident: '__nextjs_postcss',
plugins: postCssPlugins, plugins: postCssPlugins,
sourceMap: true, sourceMap: true,
}, },
...@@ -202,7 +239,7 @@ export const css = curry(async function css( ...@@ -202,7 +239,7 @@ export const css = curry(async function css(
{ {
loader: require.resolve('postcss-loader'), loader: require.resolve('postcss-loader'),
options: { options: {
ident: 'postcss', ident: '__nextjs_postcss',
plugins: postCssPlugins, plugins: postCssPlugins,
sourceMap: true, sourceMap: true,
}, },
......
...@@ -88,12 +88,12 @@ function getDefaultPlugins(): CssPluginCollection { ...@@ -88,12 +88,12 @@ function getDefaultPlugins(): CssPluginCollection {
} }
export async function getPostCssPlugins( export async function getPostCssPlugins(
dir: string dir: string,
defaults: boolean = false
): Promise<import('postcss').AcceptedPlugin[]> { ): Promise<import('postcss').AcceptedPlugin[]> {
let config = await findConfig<{ plugins: CssPluginCollection }>( let config = defaults
dir, ? null
'postcss' : await findConfig<{ plugins: CssPluginCollection }>(dir, 'postcss')
)
if (config == null) { if (config == null) {
config = { plugins: getDefaultPlugins() } config = { plugins: getDefaultPlugins() }
......
...@@ -71,6 +71,31 @@ describe('CSS Customization', () => { ...@@ -71,6 +71,31 @@ describe('CSS Customization', () => {
}) })
}) })
describe('Legacy Next-CSS Customization', () => {
const appDir = join(fixturesDir, 'custom-configuration-legacy')
beforeAll(async () => {
await remove(join(appDir, '.next'))
})
it('should build successfully', async () => {
await nextBuild(appDir)
})
it(`should've compiled and prefixed`, async () => {
const cssFolder = join(appDir, '.next/static/chunks')
const files = await readdir(cssFolder)
const cssFiles = files.filter(f => /\.css$/.test(f))
expect(cssFiles.length).toBe(1)
const cssContent = await readFile(join(cssFolder, cssFiles[0]), 'utf8')
expect(cssContent.replace(/\/\*.*?\*\//g, '').trim()).toMatchInlineSnapshot(
`"@media (480px <= width < 768px){::placeholder{color:green}}.video{max-width:400px;max-height:300px}"`
)
})
})
describe('CSS Customization Array', () => { describe('CSS Customization Array', () => {
const appDir = join(fixturesDir, 'custom-configuration-arr') const appDir = join(fixturesDir, 'custom-configuration-arr')
......
const withCSS = require('@zeit/next-css')
module.exports = withCSS({
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60,
},
experimental: {
css: true,
},
webpack(cfg) {
cfg.devtool = 'source-map'
return cfg
},
})
import React from 'react'
import App from 'next/app'
import '../styles/global.css'
class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
module.exports = {
// Use comments to test JSON5 support
plugins: [
// Test a non-standard feature that wouldn't be normally enabled
require('postcss-short-size')({
// Add a prefix to test that configuration is passed
prefix: 'xyz',
}),
],
}
/* this should pass through untransformed */
@media (480px <= width < 768px) {
::placeholder {
color: green;
}
}
/* this should be transformed to width/height */
.video {
-xyz-max-size: 400px 300px;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment