Skip to content

Commit

Permalink
Lazy-load postcss (#31762)
Browse files Browse the repository at this point in the history
Co-authored-by: Tobias Koppers <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Tobias Koppers <[email protected]>
  • Loading branch information
4 people authored Nov 25, 2021
1 parent a415932 commit 92b397f
Show file tree
Hide file tree
Showing 12 changed files with 307 additions and 303 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ test/node_modules
# logs & pids
*.log
pids
*.cpuprofile

# coverage
.nyc_output
Expand Down Expand Up @@ -41,4 +42,4 @@ test-timings.json
.now

# Cache
*.tsbuildinfo
*.tsbuildinfo
3 changes: 0 additions & 3 deletions packages/next/build/webpack-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import { NextConfigComplete } from '../server/config-shared'
import { finalizeEntrypoint } from './entries'
import * as Log from './output/log'
import { build as buildConfiguration } from './webpack/config'
import { __overrideCssConfiguration } from './webpack/config/blocks/css/overrideCssConfiguration'
import MiddlewarePlugin from './webpack/plugins/middleware-plugin'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
Expand Down Expand Up @@ -1890,8 +1889,6 @@ export default async function getBaseWebpackConfig(
(e) => (e as any).__next_css_remove !== true
)
}
} else if (!config.future.strictPostcssConfiguration) {
await __overrideCssConfiguration(dir, supportedBrowsers, webpackConfig)
}

// Inject missing React Refresh loaders so that development mode is fast:
Expand Down
188 changes: 114 additions & 74 deletions packages/next/build/webpack/config/blocks/css/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,69 +11,6 @@ import {
getLocalModuleImportError,
} from './messages'
import { getPostCssPlugins } from './plugins'
import postcss from '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.
*
* @param {string} prop String with or without vendor prefix.
*
* @return {string} vendor prefix or empty string
*
* @example
* postcss.vendor.prefix('-moz-tab-size') //=> '-moz-'
* postcss.vendor.prefix('tab-size') //=> ''
*/
prefix: function prefix(prop: any) {
const match = prop.match(/^(-\w+-)/)

if (match) {
return match[0]
}

return ''
},

/**
* Returns the input string stripped of its vendor prefix.
*
* @param {string} prop String with or without vendor prefix.
*
* @return {string} String name without vendor prefixes.
*
* @example
* postcss.vendor.unprefixed('-moz-tab-size') //=> 'tab-size'
*/
unprefixed: function unprefixed(prop: any) {
return prop.replace(/^-\w+-/, '')
},
}

// RegExps for all Style Sheet variants
export const regexLikeCss = /\.(css|scss|sass)$/
Expand All @@ -86,6 +23,99 @@ const regexCssModules = /\.module\.css$/
const regexSassGlobal = /(?<!\.module)\.(scss|sass)$/
const regexSassModules = /\.module\.(scss|sass)$/

let postcssInstancePromise: Promise<any>
export async function lazyPostCSS(
rootDirectory: string,
supportedBrowsers: string[] | undefined,
strictPostcssConfiguration: boolean | 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.
*
* @param {string} prop String with or without vendor prefix.
*
* @return {string} vendor prefix or empty string
*
* @example
* postcss.vendor.prefix('-moz-tab-size') //=> '-moz-'
* postcss.vendor.prefix('tab-size') //=> ''
*/
prefix: function prefix(prop: any) {
const match = prop.match(/^(-\w+-)/)

if (match) {
return match[0]
}

return ''
},

/**
* Returns the input string stripped of its vendor prefix.
*
* @param {string} prop String with or without vendor prefix.
*
* @return {string} String name without vendor prefixes.
*
* @example
* postcss.vendor.unprefixed('-moz-tab-size') //=> 'tab-size'
*/
unprefixed: function unprefixed(prop: any) {
return prop.replace(/^-\w+-/, '')
},
}

const postCssPlugins = await getPostCssPlugins(
rootDirectory,
supportedBrowsers,
strictPostcssConfiguration,
disablePostcssPresetEnv
)

return {
postcss,
postcssWithPlugins: postcss(postCssPlugins),
}
})()
}

return postcssInstancePromise
}

export const css = curry(async function css(
ctx: ConfigurationContext,
config: webpack.Configuration
Expand All @@ -96,6 +126,14 @@ export const css = curry(async function css(
...sassOptions
} = ctx.sassOptions

const lazyPostCSSInitalizer = () =>
lazyPostCSS(
ctx.rootDirectory,
ctx.supportedBrowsers,
ctx.future.strictPostcssConfiguration,
ctx.experimental.disablePostcssPresetEnv
)

const sassPreprocessors: webpack.RuleSetUseItem[] = [
// First, process files with `sass-loader`: this inlines content, and
// compiles away the proprietary syntax.
Expand Down Expand Up @@ -137,12 +175,6 @@ export const css = curry(async function css(
}),
]

const postCssPlugins = await getPostCssPlugins(
ctx.rootDirectory,
ctx.supportedBrowsers,
!ctx.future.strictPostcssConfiguration
)

// CSS cannot be imported in _document. This comes before everything because
// global CSS nor CSS modules work in said file.
fns.push(
Expand Down Expand Up @@ -183,7 +215,7 @@ export const css = curry(async function css(
and: [ctx.rootDirectory],
not: [/node_modules/],
},
use: getCssModuleLoader(ctx, postCssPlugins),
use: getCssModuleLoader(ctx, lazyPostCSSInitalizer),
},
],
})
Expand All @@ -206,7 +238,11 @@ export const css = curry(async function css(
and: [ctx.rootDirectory],
not: [/node_modules/],
},
use: getCssModuleLoader(ctx, postCssPlugins, sassPreprocessors),
use: getCssModuleLoader(
ctx,
lazyPostCSSInitalizer,
sassPreprocessors
),
},
],
})
Expand Down Expand Up @@ -266,7 +302,7 @@ export const css = curry(async function css(
and: [ctx.rootDirectory],
not: [/node_modules/],
},
use: getGlobalCssLoader(ctx, postCssPlugins),
use: getGlobalCssLoader(ctx, lazyPostCSSInitalizer),
},
],
})
Expand All @@ -284,7 +320,7 @@ export const css = curry(async function css(
sideEffects: true,
test: regexCssGlobal,
issuer: { and: [ctx.customAppFile] },
use: getGlobalCssLoader(ctx, postCssPlugins),
use: getGlobalCssLoader(ctx, lazyPostCSSInitalizer),
},
],
})
Expand All @@ -300,7 +336,11 @@ export const css = curry(async function css(
sideEffects: true,
test: regexSassGlobal,
issuer: { and: [ctx.customAppFile] },
use: getGlobalCssLoader(ctx, postCssPlugins, sassPreprocessors),
use: getGlobalCssLoader(
ctx,
lazyPostCSSInitalizer,
sassPreprocessors
),
},
],
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { AcceptedPlugin } from 'postcss'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { ConfigurationContext } from '../../../utils'
import { getClientStyleLoader } from './client'
import { cssFileResolve } from './file-resolve'
import postcss from 'postcss'

export function getGlobalCssLoader(
ctx: ConfigurationContext,
postCssPlugins: AcceptedPlugin[],
postcss: any,
preProcessors: readonly webpack.RuleSetUseItem[] = []
): webpack.RuleSetUseItem[] {
const loaders: webpack.RuleSetUseItem[] = []
Expand All @@ -27,6 +25,7 @@ export function getGlobalCssLoader(
loaders.push({
loader: require.resolve('../../../../loaders/css-loader/src'),
options: {
postcss,
importLoaders: 1 + preProcessors.length,
// Next.js controls CSS Modules eligibility:
modules: false,
Expand All @@ -41,7 +40,7 @@ export function getGlobalCssLoader(
loaders.push({
loader: require.resolve('../../../../loaders/postcss-loader/src'),
options: {
postcss: postcss(postCssPlugins),
postcss,
},
})

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { AcceptedPlugin } from 'postcss'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { ConfigurationContext } from '../../../utils'
import { getClientStyleLoader } from './client'
import { cssFileResolve } from './file-resolve'
import { getCssModuleLocalIdent } from './getCssModuleLocalIdent'
import postcss from 'postcss'

export function getCssModuleLoader(
ctx: ConfigurationContext,
postCssPlugins: AcceptedPlugin[],
postcss: any,
preProcessors: readonly webpack.RuleSetUseItem[] = []
): webpack.RuleSetUseItem[] {
const loaders: webpack.RuleSetUseItem[] = []
Expand All @@ -28,6 +26,7 @@ export function getCssModuleLoader(
loaders.push({
loader: require.resolve('../../../../loaders/css-loader/src'),
options: {
postcss,
importLoaders: 1 + preProcessors.length,
// Use CJS mode for backwards compatibility:
esModule: false,
Expand Down Expand Up @@ -57,7 +56,7 @@ export function getCssModuleLoader(
loaders.push({
loader: require.resolve('../../../../loaders/postcss-loader/src'),
options: {
postcss: postcss(postCssPlugins),
postcss,
},
})

Expand Down

This file was deleted.

Loading

0 comments on commit 92b397f

Please sign in to comment.