Unverified Commit 4656f52d authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

CSS Support Customization (#9502)

* CSS Support Customization

* Sort imports

* Correct PostCSS plugin loading

* Add css customization test

* Test "bad" css configuration

* Add load config test

* adjust spacing

* adjust spacing 2x

* Only allow config through JSON

* Support excluding false plugins

* Test tailwind css behavior

* Test plugin exclusion

* Fix unit test

* Fix config file

* Remove more variants

* Update test cases
parent 8357f464
...@@ -52,6 +52,7 @@ ...@@ -52,6 +52,7 @@
"clone": "2.1.2", "clone": "2.1.2",
"coveralls": "3.0.3", "coveralls": "3.0.3",
"cross-spawn": "6.0.5", "cross-spawn": "6.0.5",
"escape-string-regexp": "2.0.0",
"eslint": "6.6.0", "eslint": "6.6.0",
"eslint-plugin-react": "7.16.0", "eslint-plugin-react": "7.16.0",
"eslint-plugin-react-hooks": "2.2.0", "eslint-plugin-react-hooks": "2.2.0",
...@@ -71,6 +72,8 @@ ...@@ -71,6 +72,8 @@
"node-fetch": "2.6.0", "node-fetch": "2.6.0",
"node-notifier": "5.4.0", "node-notifier": "5.4.0",
"node-sass": "4.12.0", "node-sass": "4.12.0",
"postcss-short-size": "4.0.0",
"postcss-trolling": "0.1.7",
"pre-commit": "1.2.2", "pre-commit": "1.2.2",
"prettier": "1.19.1", "prettier": "1.19.1",
"react": "16.10.2", "react": "16.10.2",
...@@ -80,6 +83,7 @@ ...@@ -80,6 +83,7 @@
"request-promise-core": "1.1.2", "request-promise-core": "1.1.2",
"rimraf": "2.6.3", "rimraf": "2.6.3",
"shell-quote": "1.7.2", "shell-quote": "1.7.2",
"tailwindcss": "1.1.3",
"taskr": "1.1.0", "taskr": "1.1.0",
"tree-kill": "1.2.1", "tree-kill": "1.2.1",
"typescript": "3.7.2", "typescript": "3.7.2",
......
...@@ -14,6 +14,7 @@ import { ...@@ -14,6 +14,7 @@ import {
PAGES_DIR_ALIAS, PAGES_DIR_ALIAS,
} from '../lib/constants' } from '../lib/constants'
import { fileExists } from '../lib/file-exists' import { fileExists } from '../lib/file-exists'
import { findConfig } from '../lib/find-config'
import { resolveRequest } from '../lib/resolve-request' import { resolveRequest } from '../lib/resolve-request'
import { import {
CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN,
...@@ -89,6 +90,105 @@ function getOptimizedAliases(isServer: boolean): { [pkg: string]: string } { ...@@ -89,6 +90,105 @@ function getOptimizedAliases(isServer: boolean): { [pkg: string]: string } {
} }
} }
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
}
const pluginPath = resolveRequest(pkg, `${dir}/`)
if (options == null || Object.keys(options).length === 0) {
return require(pluginPath)
}
return require(pluginPath)(options)
})
.filter(Boolean)
}
const config = await findConfig<{ plugins: { [key: string]: object } }>(
dir,
'postcss'
)
let target: unknown[]
if (!config) {
target = load({
[require.resolve('postcss-flexbugs-fixes')]: {},
[require.resolve('postcss-preset-env')]: {
autoprefixer: {
// Disable legacy flexbox support
flexbox: 'no-2009',
},
// Enable CSS features that have shipped to the
// 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.`
)
}
// 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',
].forEach(plugin => {
if (!plugins.hasOwnProperty(plugin)) {
return
}
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.`
)
delete plugins[plugin]
})
// Next.js doesn't support CSS Modules yet. When we do, we should respect the
// options passed to this plugin (even though we need to remove the plugin
// itself).
if (plugins['postcss-modules']) {
delete plugins['postcss-modules']
console.warn(
`${chalk.yellow.bold(
'Warning'
)}: Next.js does not support CSS Modules (yet). The ${chalk.underline(
'postcss-modules'
)} plugin will have no effect.`
)
}
target = load(plugins as { [key: string]: object })
}
return target
}
export default async function getBaseWebpackConfig( export default async function getBaseWebpackConfig(
dir: string, dir: string,
{ {
...@@ -325,12 +425,25 @@ export default async function getBaseWebpackConfig( ...@@ -325,12 +425,25 @@ export default async function getBaseWebpackConfig(
/node_modules[/\\]/.test(module.identifier()) /node_modules[/\\]/.test(module.identifier())
) )
}, },
name(module: { libIdent: Function }): string { name(module: {
return crypto type: string
.createHash('sha1') libIdent?: Function
.update(module.libIdent({ context: dir })) updateHash: (hash: crypto.Hash) => void
.digest('hex') }): string {
.substring(0, 8) const hash = crypto.createHash('sha1')
if (module.type === `css/mini-extract`) {
module.updateHash(hash)
} else {
if (!module.libIdent) {
throw new Error(
`Encountered unknown module type: ${module.type}. Please open an issue.`
)
}
hash.update(module.libIdent({ context: dir }))
}
return hash.digest('hex').substring(0, 8)
}, },
priority: 30, priority: 30,
minChunks: 1, minChunks: 1,
...@@ -387,6 +500,10 @@ export default async function getBaseWebpackConfig( ...@@ -387,6 +500,10 @@ export default async function getBaseWebpackConfig(
customAppFile = path.resolve(path.join(pagesDir, customAppFile)) customAppFile = path.resolve(path.join(pagesDir, customAppFile))
} }
const postCssPlugins: unknown[] = config.experimental.css
? await getPostCssPlugins(dir)
: []
let webpackConfig: webpack.Configuration = { let webpackConfig: webpack.Configuration = {
devtool, devtool,
mode: webpackMode, mode: webpackMode,
...@@ -717,20 +834,7 @@ export default async function getBaseWebpackConfig( ...@@ -717,20 +834,7 @@ export default async function getBaseWebpackConfig(
loader: require.resolve('postcss-loader'), loader: require.resolve('postcss-loader'),
options: { options: {
ident: 'postcss', ident: 'postcss',
plugins: () => [ plugins: postCssPlugins,
// Make Flexbox behave like the spec cross-browser.
require('postcss-flexbugs-fixes'),
// Run Autoprefixer and compile new CSS features.
require('postcss-preset-env')({
autoprefixer: {
// Disable legacy flexbox support
flexbox: 'no-2009',
},
// Enable CSS features that have shipped to the
// web platform, i.e. in 2+ browsers unflagged.
stage: 3,
}),
],
sourceMap: true, sourceMap: true,
}, },
}, },
......
import findUp from 'find-up'
import fs from 'fs'
import JSON5 from 'json5'
type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>
}
// We'll allow configuration to be typed, but we force everything provided to
// become optional. We do not perform any schema validation. We should maybe
// force all the types to be `unknown` as well.
export async function findConfig<T>(
directory: string,
key: string
): Promise<RecursivePartial<T> | null> {
// `package.json` configuration always wins. Let's check that first.
const packageJsonPath = await findUp('package.json', { cwd: directory })
if (packageJsonPath) {
const packageJson = require(packageJsonPath)
if (packageJson[key] != null && typeof packageJson[key] === 'object') {
return packageJson[key]
}
}
// If we didn't find the configuration in `package.json`, we should look for
// known filenames. The /rc$/ version of this file does not support YAML
// like some configuration loaders.
const filePath = await findUp(`.${key}rc.json`, {
cwd: directory,
})
if (filePath) {
// We load JSON contents with JSON5 to allow users to comment in their
// configuration file. This pattern was popularized by TypeScript.
const fileContents = fs.readFileSync(filePath, 'utf8')
return JSON5.parse(fileContents)
}
return null
}
...@@ -96,6 +96,7 @@ ...@@ -96,6 +96,7 @@
"is-docker": "2.0.0", "is-docker": "2.0.0",
"is-wsl": "2.1.1", "is-wsl": "2.1.1",
"jest-worker": "24.9.0", "jest-worker": "24.9.0",
"json5": "2.1.1",
"launch-editor": "2.2.1", "launch-editor": "2.2.1",
"loader-utils": "1.2.3", "loader-utils": "1.2.3",
"lru-cache": "5.1.1", "lru-cache": "5.1.1",
...@@ -153,6 +154,7 @@ ...@@ -153,6 +154,7 @@
"@types/etag": "1.8.0", "@types/etag": "1.8.0",
"@types/find-up": "2.1.1", "@types/find-up": "2.1.1",
"@types/fresh": "0.5.0", "@types/fresh": "0.5.0",
"@types/json5": "0.0.30",
"@types/loader-utils": "1.1.3", "@types/loader-utils": "1.1.3",
"@types/lru-cache": "5.1.0", "@types/lru-cache": "5.1.0",
"@types/mini-css-extract-plugin": "0.8.0", "@types/mini-css-extract-plugin": "0.8.0",
......
{
"sourceMap": false,
"plugins": {
"postcss-modules-extract-imports": {},
"postcss-modules-local-by-default": {},
"postcss-modules-scope": {},
"postcss-modules-values": {},
"postcss-modules": {},
// Test a non-standard feature that wouldn't be normally enabled
"postcss-short-size": {}
}
}
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
export default function Home() {
return <div />
}
/* this should be transformed to width/height */
.video {
max-size: 400px 300px;
}
{
// Use comments to test JSON5 support
"plugins": {
// Test a non-standard feature that wouldn't be normally enabled
"postcss-short-size": {
// Add a prefix to test that configuration is passed
"prefix": "xyz"
},
"postcss-trolling": false
}
}
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
export default function Home() {
return <div />
}
/* 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;
}
{
"postcss": {
"plugins": {
"tailwindcss": {}
}
}
}
import '../styles/global.css'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default function Home() {
return <div />
}
@tailwind base;
@tailwind components;
@tailwind utilities;
...@@ -15,6 +15,7 @@ import { ...@@ -15,6 +15,7 @@ import {
renderViaHTTP, renderViaHTTP,
} from 'next-test-utils' } from 'next-test-utils'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import escapeStringRegexp from 'escape-string-regexp'
import cheerio from 'cheerio' import cheerio from 'cheerio'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2
...@@ -218,6 +219,119 @@ describe('CSS Support', () => { ...@@ -218,6 +219,119 @@ describe('CSS Support', () => {
}) })
}) })
describe('CSS Customization', () => {
const appDir = join(fixturesDir, 'custom-configuration')
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/css')
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}"`
)
// Contains a source map
expect(cssContent).toMatch(/\/\*#\s*sourceMappingURL=(.+\.map)\s*\*\//)
})
it(`should've emitted a source map`, async () => {
const cssFolder = join(appDir, '.next/static/css')
const files = await readdir(cssFolder)
const cssMapFiles = files.filter(f => /\.css\.map$/.test(f))
expect(cssMapFiles.length).toBe(1)
const cssMapContent = (
await readFile(join(cssFolder, cssMapFiles[0]), 'utf8')
).trim()
const { version, mappings, sourcesContent } = JSON.parse(cssMapContent)
expect({ version, mappings, sourcesContent }).toMatchInlineSnapshot(`
Object {
"mappings": "AACA,gCACE,cACE,WACF,CACF,CAGA,OACE,eAA0B,CAA1B,gBACF",
"sourcesContent": Array [
"/* 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;
}
",
],
"version": 3,
}
`)
})
})
describe('Bad CSS Customization', () => {
const appDir = join(fixturesDir, 'bad-custom-configuration')
beforeAll(async () => {
await remove(join(appDir, '.next'))
})
it('should build successfully', async () => {
const { stderr } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).toMatch(/field which is not supported.*?sourceMap/)
;[
'postcss-modules-values',
'postcss-modules-scope',
'postcss-modules-extract-imports',
'postcss-modules-local-by-default',
].forEach(plugin => {
expect(stderr).toMatch(
new RegExp(`Please remove the.*?${escapeStringRegexp(plugin)}`)
)
})
})
it(`should've compiled and prefixed`, async () => {
const cssFolder = join(appDir, '.next/static/css')
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(`".video{max-width:400px;max-height:300px}"`)
// Contains a source map
expect(cssContent).toMatch(/\/\*#\s*sourceMappingURL=(.+\.map)\s*\*\//)
})
it(`should've emitted a source map`, async () => {
const cssFolder = join(appDir, '.next/static/css')
const files = await readdir(cssFolder)
const cssMapFiles = files.filter(f => /\.css\.map$/.test(f))
expect(cssMapFiles.length).toBe(1)
})
})
// Tests css ordering // Tests css ordering
describe('Multi Global Support (reversed)', () => { describe('Multi Global Support (reversed)', () => {
const appDir = join(fixturesDir, 'multi-global-reversed') const appDir = join(fixturesDir, 'multi-global-reversed')
...@@ -649,4 +763,41 @@ describe('CSS Support', () => { ...@@ -649,4 +763,41 @@ describe('CSS Support', () => {
} }
}) })
}) })
describe('Basic Tailwind CSS', () => {
const appDir = join(fixturesDir, 'with-tailwindcss')
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/css')
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).toMatch(/object-right-bottom/) // look for tailwind's CSS
expect(cssContent).not.toMatch(/tailwind/) // ensure @tailwind was removed
// Contains a source map
expect(cssContent).toMatch(/\/\*#\s*sourceMappingURL=(.+\.map)\s*\*\//)
})
it(`should've emitted a source map`, async () => {
const cssFolder = join(appDir, '.next/static/css')
const files = await readdir(cssFolder)
const cssMapFiles = files.filter(f => /\.css\.map$/.test(f))
expect(cssMapFiles.length).toBe(1)
})
})
}) })
/* eslint-env jest */
import { findConfig } from 'next/dist/lib/find-config'
import { join } from 'path'
const fixtureDir = join(__dirname, 'fixtures')
describe('find config', () => {
it('should resolve rc.json', async () => {
const config = await findConfig(join(fixtureDir, 'config-json'), 'test')
expect(config).toEqual({ foo: 'bar' })
})
it('should resolve package.json', async () => {
const config = await findConfig(
join(fixtureDir, 'config-package-json'),
'test'
)
expect(config).toEqual({ foo: 'bar' })
})
it('should resolve down', async () => {
const config = await findConfig(
join(fixtureDir, 'config-down/one/two/three/'),
'test'
)
expect(config).toEqual({ foo: 'bar' })
})
})
This diff is collapsed.
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