Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redesign PostCSS Configuration Loading #9704

Merged
merged 5 commits into from
Dec 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@
"node-notifier": "5.4.0",
"node-sass": "4.12.0",
"npm-run-all": "4.1.5",
"pixrem": "5.0.0",
"postcss-pseudoelements": "5.0.0",
"postcss-short-size": "4.0.0",
"postcss-trolling": "0.1.7",
"pre-commit": "1.2.2",
Expand Down
223 changes: 163 additions & 60 deletions packages/next/build/webpack/config/blocks/css/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,79 @@ import chalk from 'chalk'
import { findConfig } from '../../../../../lib/find-config'
import { resolveRequest } from '../../../../../lib/resolve-request'

export async function getPostCssPlugins(dir: string): Promise<unknown[]> {
function load(plugins: { [key: string]: object | false }): unknown[] {
return Object.keys(plugins)
.map(pkg => {
const options = plugins[pkg]
if (options === false) {
return false
}
type CssPluginCollection_Array = (string | [string, boolean | object])[]

const pluginPath = resolveRequest(pkg, `${dir}/`)
type CssPluginCollection_Object = { [key: string]: object | boolean }

if (options == null || Object.keys(options).length === 0) {
return require(pluginPath)
}
return require(pluginPath)(options)
})
.filter(Boolean)
type CssPluginCollection =
| CssPluginCollection_Array
| CssPluginCollection_Object

type CssPluginShape = [string, object | boolean]

const genericErrorText = 'Malformed PostCSS Configuration'

function getError_NullConfig(pluginName: string) {
return `${chalk.red.bold(
'Error'
)}: Your PostCSS configuration for '${pluginName}' cannot have ${chalk.bold(
'null'
)} configuration.\nTo disable '${pluginName}', pass ${chalk.bold(
'false'
)}, otherwise, pass ${chalk.bold('true')} or a configuration object.`
}

function isIgnoredPlugin(pluginPath: string): boolean {
const ignoredRegex = /(?:^|[\\/])(postcss-modules-values|postcss-modules-scope|postcss-modules-extract-imports|postcss-modules-local-by-default|postcss-modules)(?:[\\/]|$)/i
const match = ignoredRegex.exec(pluginPath)
if (match == null) {
return false
}

const config = await findConfig<{ plugins: { [key: string]: object } }>(
dir,
'postcss'
const plugin = match.pop()!
console.warn(
`${chalk.yellow.bold('Warning')}: Please remove the ${chalk.underline(
plugin
)} plugin from your PostCSS configuration. ` +
`This plugin is automatically configured by Next.js.`
)
return true
}

async function loadPlugin(
dir: string,
pluginName: string,
options: boolean | object
): Promise<import('postcss').AcceptedPlugin | false> {
if (options === false || isIgnoredPlugin(pluginName)) {
return false
}

let target: unknown[]
if (options == null) {
console.error(getError_NullConfig(pluginName))
throw new Error(genericErrorText)
}

if (!config) {
target = load({
[require.resolve('postcss-flexbugs-fixes')]: {},
[require.resolve('postcss-preset-env')]: {
const pluginPath = resolveRequest(pluginName, `${dir}/`)
if (isIgnoredPlugin(pluginPath)) {
return false
} else if (options === true) {
return require(pluginPath)
} else {
const keys = Object.keys(options)
if (keys.length === 0) {
return require(pluginPath)
}
return require(pluginPath)(options)
}
}

function getDefaultPlugins(): CssPluginCollection {
return [
require.resolve('postcss-flexbugs-fixes'),
[
require.resolve('postcss-preset-env'),
{
autoprefixer: {
// Disable legacy flexbox support
flexbox: 'no-2009',
Expand All @@ -40,49 +83,109 @@ export async function getPostCssPlugins(dir: string): Promise<unknown[]> {
// web platform, i.e. in 2+ browsers unflagged.
stage: 3,
},
})
} else {
const plugins = config.plugins
if (plugins == null || typeof plugins !== 'object') {
throw new Error(
`Your custom PostCSS configuration must export a \`plugins\` key.`
)
}
],
]
}

const invalidKey = Object.keys(config).find(key => key !== 'plugins')
if (invalidKey) {
console.warn(
`${chalk.yellow.bold(
'Warning'
)}: Your PostCSS configuration defines a field which is not supported (\`${invalidKey}\`). ` +
`Please remove this configuration value.`
)
}
export async function getPostCssPlugins(
dir: string
): Promise<import('postcss').AcceptedPlugin[]> {
let config = await findConfig<{ plugins: CssPluginCollection }>(
dir,
'postcss'
)

// These plugins cannot be enabled by the user because they'll conflict with
// `css-loader`'s behavior to make us compatible with webpack.
;[
'postcss-modules-values',
'postcss-modules-scope',
'postcss-modules-extract-imports',
'postcss-modules-local-by-default',
'postcss-modules',
].forEach(plugin => {
if (!plugins.hasOwnProperty(plugin)) {
return
if (config == null) {
config = { plugins: getDefaultPlugins() }
}

// Warn user about configuration keys which are not respected
const invalidKey = Object.keys(config).find(key => key !== 'plugins')
if (invalidKey) {
console.warn(
`${chalk.yellow.bold(
'Warning'
)}: Your PostCSS configuration defines a field which is not supported (\`${invalidKey}\`). ` +
`Please remove this configuration value.`
)
}

// Enforce the user provided plugins if the configuration file is present
let plugins = config.plugins
if (plugins == null || typeof plugins !== 'object') {
throw new Error(
`Your custom PostCSS configuration must export a \`plugins\` key.`
)
}

if (!Array.isArray(plugins)) {
// Capture variable so TypeScript is happy
const pc = plugins

plugins = Object.keys(plugins).reduce((acc, curr) => {
const p = pc[curr]
if (typeof p === 'undefined') {
console.error(getError_NullConfig(curr))
throw new Error(genericErrorText)
}

acc.push([curr, p])
return acc
}, [] as CssPluginCollection_Array)
}

const parsed: CssPluginShape[] = []
plugins.forEach(plugin => {
if (plugin == null) {
console.warn(
`${chalk.yellow.bold('Warning')}: Please remove the ${chalk.underline(
plugin
)} plugin from your PostCSS configuration. ` +
`This plugin is automatically configured by Next.js.`
`${chalk.yellow.bold('Warning')}: A ${chalk.bold(
'null'
)} PostCSS plugin was provided. This entry will be ignored.`
)
} else if (typeof plugin === 'string') {
parsed.push([plugin, true])
} else if (Array.isArray(plugin)) {
const pluginName = plugin[0]
const pluginConfig = plugin[1]
if (
typeof pluginName === 'string' &&
(typeof pluginConfig === 'boolean' || typeof pluginConfig === 'object')
) {
parsed.push([pluginName, pluginConfig])
} else {
if (typeof pluginName !== 'string') {
console.error(
`${chalk.red.bold(
'Error'
)}: A PostCSS Plugin must be provided as a ${chalk.bold(
'string'
)}. Instead, we got: '${pluginName}'.`
)
} else {
console.error(
`${chalk.red.bold(
'Error'
)}: A PostCSS Plugin was passed as an array but did not provide its configuration ('${pluginName}').`
)
}
throw new Error(genericErrorText)
}
} else {
console.error(
`${chalk.red.bold(
'Error'
)}: An unknown PostCSS plugin was provided (${plugin}).`
)
delete plugins[plugin]
})
throw new Error(genericErrorText)
}
})

target = load(plugins as { [key: string]: object })
}
const resolved = await Promise.all(
parsed.map(p => loadPlugin(dir, p[0], p[1]))
)
const filtered: import('postcss').AcceptedPlugin[] = resolved.filter(
Boolean
) as import('postcss').AcceptedPlugin[]

return target
return filtered
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"plugins": [["postcss-trolling"]]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Home() {
return <div />
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/* this should pass through untransformed */
@media (480px <= width < 768px) {
a::before {
content: '';
}
::placeholder {
color: green;
}
}

/* this should be transformed to width/height */
.video {
-xyz-max-size: 400rem 300rem;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"plugins": [["postcss-trolling", null]]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Home() {
return <div />
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/* this should pass through untransformed */
@media (480px <= width < 768px) {
a::before {
content: '';
}
::placeholder {
color: green;
}
}

/* this should be transformed to width/height */
.video {
-xyz-max-size: 400rem 300rem;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"plugins": [[5, null]]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Home() {
return <div />
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/* this should pass through untransformed */
@media (480px <= width < 768px) {
a::before {
content: '';
}
::placeholder {
color: green;
}
}

/* this should be transformed to width/height */
.video {
-xyz-max-size: 400rem 300rem;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"plugins": [5]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Home() {
return <div />
}
Loading