Commit 734989d8 authored by Joe Haddad's avatar Joe Haddad Committed by Tim Neutkens

[Experimental] CSS Module Support (#9686)

* CSS Module Support

* Fix Server-Side Render of CSS Modules

* Fix Jest Snapshots
https://github.com/facebook/jest/pull/8492

* Fix snapshots

* Add test for CSS module edit without remounting

* Add tests for dev and production style being applied

* Add missing TODOs

* Include/exclude should only be applied to issuer, not the CSS file itself

* Add CSS modules + node_modules tests

* Test that content is correct

* Create Multi Module Suite

* Add client-side navigation support for CSS

* Add tests for client-side nav

* Add some delays

* Try another fix

* Increase timeout to 3 minutes

* Fix test

* Give all unique directories
parent bc7fd2d8
import loaderUtils from 'loader-utils'
import path from 'path'
import webpack from 'webpack'
export function getCssModuleLocalIdent(
context: webpack.loader.LoaderContext,
_: any,
exportName: string,
options: object
) {
const relativePath = path.posix.relative(
context.rootContext,
context.resourcePath
)
// Generate a more meaningful name (parent folder) when the user names the
// file `index.module.css`.
const fileNameOrFolder =
relativePath.endsWith('index.module.css') &&
relativePath !== 'pages/index.module.css'
? '[folder]'
: '[name]'
// Generate a hash to make the class name unique.
const hash = loaderUtils.getHashDigest(
Buffer.from(`filePath:${relativePath}#className:${exportName}`),
'md5',
'base64',
5
)
// Have webpack interpolate the `[folder]` or `[name]` to its real value.
return loaderUtils
.interpolateName(
context,
fileNameOrFolder + '_' + exportName + '__' + hash,
options
)
.replace(
// Webpack name interpolation returns `about.module_root__2oFM9` for
// `.root {}` inside a file named `about.module.css`. Let's simplify
// this.
/\.module_/,
'_'
)
}
import curry from 'lodash.curry' import curry from 'lodash.curry'
import MiniCssExtractPlugin from 'mini-css-extract-plugin' import MiniCssExtractPlugin from 'mini-css-extract-plugin'
import path from 'path' import path from 'path'
import { Configuration } from 'webpack' import webpack, { Configuration } from 'webpack'
import { loader } from '../../helpers' import { loader } from '../../helpers'
import { ConfigurationContext, ConfigurationFn, pipe } from '../../utils' import { ConfigurationContext, ConfigurationFn, pipe } from '../../utils'
import { getGlobalImportError } from './messages' import { getCssModuleLocalIdent } from './getCssModuleLocalIdent'
import { getGlobalImportError, getModuleImportError } from './messages'
import { getPostCssPlugins } from './plugins' import { getPostCssPlugins } from './plugins'
import webpack from 'webpack'
function getStyleLoader({ function getClientStyleLoader({
isDevelopment, isDevelopment,
}: { }: {
isDevelopment: boolean isDevelopment: boolean
...@@ -73,6 +73,86 @@ export const css = curry(async function css( ...@@ -73,6 +73,86 @@ export const css = curry(async function css(
const fns: ConfigurationFn[] = [] const fns: ConfigurationFn[] = []
const postCssPlugins = await getPostCssPlugins(ctx.rootDirectory)
// CSS Modules support must be enabled on the server and client so the class
// names are availble for SSR or Prerendering.
fns.push(
loader({
oneOf: [
{
// CSS Modules should never have side effects. This setting will
// allow unused CSS to be removed from the production build.
// We ensure this by disallowing `:global()` CSS at the top-level
// via the `pure` mode in `css-loader`.
sideEffects: false,
// CSS Modules are activated via this specific extension.
test: /\.module\.css$/,
// CSS Modules are only supported in the user's application. We're
// not yet allowing CSS imports _within_ `node_modules`.
issuer: {
include: [ctx.rootDirectory],
exclude: /node_modules/,
},
use: ([
// Add appropriate development more or production mode style
// loader
ctx.isClient &&
getClientStyleLoader({ isDevelopment: ctx.isDevelopment }),
// Resolve CSS `@import`s and `url()`s
{
loader: require.resolve('css-loader'),
options: {
importLoaders: 1,
sourceMap: true,
onlyLocals: ctx.isServer,
modules: {
// Disallow global style exports so we can code-split CSS and
// not worry about loading order.
mode: 'pure',
// Generate a friendly production-ready name so it's
// reasonably understandable. The same name is used for
// development.
// TODO: Consider making production reduce this to a single
// character?
getLocalIdent: getCssModuleLocalIdent,
},
},
},
// Compile CSS
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: postCssPlugins,
sourceMap: true,
},
},
] as webpack.RuleSetUseItem[]).filter(Boolean),
},
],
})
)
// Throw an error for CSS Modules used outside their supported scope
fns.push(
loader({
oneOf: [
{
test: /\.module\.css$/,
use: {
loader: 'error-loader',
options: {
reason: getModuleImportError(),
},
},
},
],
})
)
if (ctx.isServer) { if (ctx.isServer) {
fns.push( fns.push(
loader({ loader({
...@@ -80,7 +160,6 @@ export const css = curry(async function css( ...@@ -80,7 +160,6 @@ export const css = curry(async function css(
}) })
) )
} else if (ctx.customAppFile) { } else if (ctx.customAppFile) {
const postCssPlugins = await getPostCssPlugins(ctx.rootDirectory)
fns.push( fns.push(
loader({ loader({
oneOf: [ oneOf: [
...@@ -96,7 +175,7 @@ export const css = curry(async function css( ...@@ -96,7 +175,7 @@ export const css = curry(async function css(
use: [ use: [
// Add appropriate development more or production mode style // Add appropriate development more or production mode style
// loader // loader
getStyleLoader({ isDevelopment: ctx.isDevelopment }), getClientStyleLoader({ isDevelopment: ctx.isDevelopment }),
// Resolve CSS `@import`s and `url()`s // Resolve CSS `@import`s and `url()`s
{ {
......
...@@ -9,3 +9,10 @@ export function getGlobalImportError(file: string | null) { ...@@ -9,3 +9,10 @@ export function getGlobalImportError(file: string | null) {
file ? file : 'pages/_app.js' file ? file : 'pages/_app.js'
)}.\nRead more: https://err.sh/next.js/global-css` )}.\nRead more: https://err.sh/next.js/global-css`
} }
export function getModuleImportError() {
// TODO: Read more link
return `CSS Modules ${chalk.bold(
'cannot'
)} be imported from within ${chalk.bold('node_modules')}.`
}
...@@ -11,12 +11,20 @@ function supportsPreload(el) { ...@@ -11,12 +11,20 @@ function supportsPreload(el) {
const hasPreload = supportsPreload(document.createElement('link')) const hasPreload = supportsPreload(document.createElement('link'))
function preloadScript(url) { function preloadLink(url, resourceType) {
const link = document.createElement('link') const link = document.createElement('link')
link.rel = 'preload' link.rel = 'preload'
link.crossOrigin = process.crossOrigin link.crossOrigin = process.crossOrigin
link.href = url link.href = url
link.as = 'script' link.as = resourceType
document.head.appendChild(link)
}
function loadStyle(url) {
const link = document.createElement('link')
link.rel = 'stylesheet'
link.crossOrigin = process.crossOrigin
link.href = url
document.head.appendChild(link) document.head.appendChild(link)
} }
...@@ -105,6 +113,12 @@ export default class PageLoader { ...@@ -105,6 +113,12 @@ export default class PageLoader {
) { ) {
this.loadScript(d, route, false) this.loadScript(d, route, false)
} }
if (
/\.css$/.test(d) &&
!document.querySelector(`link[rel=stylesheet][href^="${d}"]`)
) {
loadStyle(d) // FIXME: handle failure
}
}) })
this.loadRoute(route) this.loadRoute(route)
this.loadingRoutes[route] = true this.loadingRoutes[route] = true
...@@ -228,7 +242,7 @@ export default class PageLoader { ...@@ -228,7 +242,7 @@ export default class PageLoader {
// If not fall back to loading script tags before the page is loaded // If not fall back to loading script tags before the page is loaded
// https://caniuse.com/#feat=link-rel-preload // https://caniuse.com/#feat=link-rel-preload
if (hasPreload) { if (hasPreload) {
preloadScript(url) preloadLink(url, url.match(/\.css$/) ? 'style' : 'script')
return return
} }
......
...@@ -87,7 +87,7 @@ ...@@ -87,7 +87,7 @@
"conf": "5.0.0", "conf": "5.0.0",
"content-type": "1.0.4", "content-type": "1.0.4",
"cookie": "0.4.0", "cookie": "0.4.0",
"css-loader": "3.2.0", "css-loader": "3.3.0",
"cssnano-simple": "1.0.0", "cssnano-simple": "1.0.0",
"devalue": "2.0.1", "devalue": "2.0.1",
"etag": "1.8.1", "etag": "1.8.1",
......
import { redText } from './index.module.css'
export default function Home() {
return (
<div id="verify-red" className={redText}>
This text should be red.
</div>
)
}
import { redText } from './index.module.css'
export default function Home() {
return (
<div id="verify-red" className={redText}>
This text should be red.
</div>
)
}
import { redText } from './index.module.css'
function Home() {
return (
<>
<div id="verify-red" className={redText}>
This text should be red.
</div>
<br />
<input key={'' + Math.random()} id="text-input" type="text" />
</>
)
}
export default Home
import * as classes from 'example'
function Home() {
return <div>This should fail at build time {JSON.stringify(classes)}.</div>
}
export default Home
import Link from 'next/link'
import { blueText } from './blue.module.css'
export default function Blue() {
return (
<>
<div id="verify-blue" className={blueText}>
This text should be blue.
</div>
<br />
<Link href="/red" prefetch>
<a id="link-red">Red</a>
</Link>
<br />
<Link href="/none" prefetch={false}>
<a id="link-none">None</a>
</Link>
</>
)
}
import Link from 'next/link'
export default function None() {
return (
<>
<div id="verify-black" style={{ color: 'black' }}>
This text should be black.
</div>
<br />
<Link href="/red" prefetch={false}>
<a id="link-red">Red</a>
</Link>
<br />
<Link href="/blue" prefetch={false}>
<a id="link-blue">Blue</a>
</Link>
</>
)
}
import Link from 'next/link'
import { redText } from './red.module.css'
export default function Red() {
return (
<>
<div id="verify-red" className={redText}>
This text should be red.
</div>
<br />
<Link href="/blue" prefetch={false}>
<a id="link-blue">Blue</a>
</Link>
<br />
<Link href="/none" prefetch={false}>
<a id="link-none">None</a>
</Link>
</>
)
}
const message = 'Why hello there'
module.exports = { message }
import * as data from 'example'
import * as classes from 'example/index.module.css'
function Home() {
return (
<div id="nm-div">
{JSON.stringify(data)} {JSON.stringify(classes)}
</div>
)
}
export default Home
import { redText } from './index.module.css'
export default function Home() {
return (
<div id="verify-red" className={redText}>
This text should be red.
</div>
)
}
This diff is collapsed.
...@@ -5420,23 +5420,23 @@ css-loader@1.0.0: ...@@ -5420,23 +5420,23 @@ css-loader@1.0.0:
postcss-value-parser "^3.3.0" postcss-value-parser "^3.3.0"
source-list-map "^2.0.0" source-list-map "^2.0.0"
css-loader@3.2.0: css-loader@3.3.0:
version "3.2.0" version "3.3.0"
resolved "https://registry.yarnpkg.com/css-loader/-/css-loader-3.2.0.tgz#bb570d89c194f763627fcf1f80059c6832d009b2" resolved "https://registry.yarnpkg.com/css-loader/-/css-loader-3.3.0.tgz#65f889807baec3197313965d6cda9899f936734d"
integrity sha512-QTF3Ud5H7DaZotgdcJjGMvyDj5F3Pn1j/sC6VBEOVp94cbwqyIBdcs/quzj4MC1BKQSrTpQznegH/5giYbhnCQ== integrity sha512-x9Y1vvHe5RR+4tzwFdWExPueK00uqFTCw7mZy+9aE/X1SKWOArm5luaOrtJ4d05IpOwJ6S86b/tVcIdhw1Bu4A==
dependencies: dependencies:
camelcase "^5.3.1" camelcase "^5.3.1"
cssesc "^3.0.0" cssesc "^3.0.0"
icss-utils "^4.1.1" icss-utils "^4.1.1"
loader-utils "^1.2.3" loader-utils "^1.2.3"
normalize-path "^3.0.0" normalize-path "^3.0.0"
postcss "^7.0.17" postcss "^7.0.23"
postcss-modules-extract-imports "^2.0.0" postcss-modules-extract-imports "^2.0.0"
postcss-modules-local-by-default "^3.0.2" postcss-modules-local-by-default "^3.0.2"
postcss-modules-scope "^2.1.0" postcss-modules-scope "^2.1.1"
postcss-modules-values "^3.0.0" postcss-modules-values "^3.0.0"
postcss-value-parser "^4.0.0" postcss-value-parser "^4.0.2"
schema-utils "^2.0.0" schema-utils "^2.6.0"
css-prefers-color-scheme@^3.1.1: css-prefers-color-scheme@^3.1.1:
version "3.1.1" version "3.1.1"
...@@ -12213,10 +12213,10 @@ postcss-modules-scope@^1.1.0: ...@@ -12213,10 +12213,10 @@ postcss-modules-scope@^1.1.0:
css-selector-tokenizer "^0.7.0" css-selector-tokenizer "^0.7.0"
postcss "^6.0.1" postcss "^6.0.1"
postcss-modules-scope@^2.1.0: postcss-modules-scope@^2.1.1:
version "2.1.0" version "2.1.1"
resolved "https://registry.yarnpkg.com/postcss-modules-scope/-/postcss-modules-scope-2.1.0.tgz#ad3f5bf7856114f6fcab901b0502e2a2bc39d4eb" resolved "https://registry.yarnpkg.com/postcss-modules-scope/-/postcss-modules-scope-2.1.1.tgz#33d4fc946602eb5e9355c4165d68a10727689dba"
integrity sha512-91Rjps0JnmtUB0cujlc8KIKCsJXWjzuxGeT/+Q2i2HXKZ7nBUeF9YQTZZTNvHVoNYj1AthsjnGLtqDUE0Op79A== integrity sha512-OXRUPecnHCg8b9xWvldG/jUpRIGPNRka0r4D4j0ESUU2/5IOnpsjfPPmDprM3Ih8CgZ8FXjWqaniK5v4rWt3oQ==
dependencies: dependencies:
postcss "^7.0.6" postcss "^7.0.6"
postcss-selector-parser "^6.0.0" postcss-selector-parser "^6.0.0"
...@@ -13759,6 +13759,14 @@ schema-utils@^2.0.0, schema-utils@^2.0.1: ...@@ -13759,6 +13759,14 @@ schema-utils@^2.0.0, schema-utils@^2.0.1:
ajv "^6.10.2" ajv "^6.10.2"
ajv-keywords "^3.4.1" ajv-keywords "^3.4.1"
schema-utils@^2.6.0:
version "2.6.1"
resolved "https://registry.yarnpkg.com/schema-utils/-/schema-utils-2.6.1.tgz#eb78f0b945c7bcfa2082b3565e8db3548011dc4f"
integrity sha512-0WXHDs1VDJyo+Zqs9TKLKyD/h7yDpHUhEFsM2CzkICFdoX1av+GBq/J2xRTFfsQO5kBfhZzANf2VcIm84jqDbg==
dependencies:
ajv "^6.10.2"
ajv-keywords "^3.4.1"
scss-tokenizer@^0.2.3: scss-tokenizer@^0.2.3:
version "0.2.3" version "0.2.3"
resolved "https://registry.yarnpkg.com/scss-tokenizer/-/scss-tokenizer-0.2.3.tgz#8eb06db9a9723333824d3f5530641149847ce5d1" resolved "https://registry.yarnpkg.com/scss-tokenizer/-/scss-tokenizer-0.2.3.tgz#8eb06db9a9723333824d3f5530641149847ce5d1"
......
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