Unverified Commit 65358b7a authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Global CSS Support (#8710)

* Global CSS Support

* Fix webpack configuration

* oneOf rule isn't necessary yet

* Adjust CSS chunk naming

* Begin testing CSS behavior

* Add another test TODO

* Replace null-loader with ignore-loader

* Turn on chunks for new CSS feature

* Fix multi test suite

* Test CSS import order

* Test style HMR

* Test CSS compilation

* Test compilation and prefixing together

* Verify CSS styling works for Development and Production

* Add missing TODO

* Remove unnecessary test

* Adjust TODO message

* Hide page until React hydrates

* Revert "Hide page until React hydrates"

This reverts commit 898d4e0ee547b003d5790e2b11476740d645b907.

* Hide FOUC during development

* Test CSS imports

* Update tests TODO

* Add fixture for url() test

* Test `file-loader` support in CSS files

* Use a simple variant of cssnano

* Self-import

* Undo bundling

* Implement suggestion
parent 20aa1e4d
import crypto from 'crypto' import crypto from 'crypto'
import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin' import ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin'
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
import OptimizeCssAssetsPlugin from 'optimize-css-assets-webpack-plugin'
import path from 'path' import path from 'path'
// @ts-ignore: Currently missing types // @ts-ignore: Currently missing types
import PnpWebpackPlugin from 'pnp-webpack-plugin' import PnpWebpackPlugin from 'pnp-webpack-plugin'
...@@ -20,6 +22,7 @@ import { ...@@ -20,6 +22,7 @@ import {
SERVER_DIRECTORY, SERVER_DIRECTORY,
SERVERLESS_DIRECTORY, SERVERLESS_DIRECTORY,
} from '../next-server/lib/constants' } from '../next-server/lib/constants'
import { findPageFile } from '../server/lib/find-page-file'
import { WebpackEntrypoints } from './entries' import { WebpackEntrypoints } from './entries'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin' import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import { ChunkGraphPlugin } from './webpack/plugins/chunk-graph-plugin' import { ChunkGraphPlugin } from './webpack/plugins/chunk-graph-plugin'
...@@ -291,6 +294,17 @@ export default async function getBaseWebpackConfig( ...@@ -291,6 +294,17 @@ export default async function getBaseWebpackConfig(
? 'anonymous' ? 'anonymous'
: config.crossOrigin : config.crossOrigin
let customAppFile: string | null = config.experimental.css
? await findPageFile(
path.join(dir, 'pages'),
'/_app',
config.pageExtensions
)
: null
if (customAppFile) {
customAppFile = path.resolve(path.join(dir, 'pages', customAppFile))
}
let webpackConfig: webpack.Configuration = { let webpackConfig: webpack.Configuration = {
devtool, devtool,
mode: webpackMode, mode: webpackMode,
...@@ -419,11 +433,26 @@ export default async function getBaseWebpackConfig( ...@@ -419,11 +433,26 @@ export default async function getBaseWebpackConfig(
: { name: CLIENT_STATIC_FILES_RUNTIME_WEBPACK }, : { name: CLIENT_STATIC_FILES_RUNTIME_WEBPACK },
minimize: !(dev || isServer), minimize: !(dev || isServer),
minimizer: [ minimizer: [
// Minify JavaScript
new TerserPlugin({ new TerserPlugin({
...terserPluginConfig, ...terserPluginConfig,
terserOptions, terserOptions,
}), }),
], // Minify CSS
config.experimental.css &&
new OptimizeCssAssetsPlugin({
cssProcessorOptions: {
map: {
// `inline: false` generates the source map in a separate file.
// Otherwise, the CSS file is needlessly large.
inline: false,
// `annotation: true` appends the `sourceMappingURL` to the end
// of the CSS file for DevTools to find them.
annotation: true,
},
},
}),
].filter(Boolean),
}, },
recordsPath: path.join(outputPath, 'records.json'), recordsPath: path.join(outputPath, 'records.json'),
context: dir, context: dir,
...@@ -518,6 +547,75 @@ export default async function getBaseWebpackConfig( ...@@ -518,6 +547,75 @@ export default async function getBaseWebpackConfig(
}, },
use: defaultLoaders.babel, use: defaultLoaders.babel,
}, },
config.experimental.css &&
// Support CSS imports
({
test: /\.css$/,
issuer: { include: [customAppFile].filter(Boolean) },
use: isServer
? // Global CSS is ignored on the server because it's only needed
// on the client-side.
require.resolve('ignore-loader')
: [
// During development we load CSS via JavaScript so we can
// hot reload it without refreshing the page.
dev && require.resolve('style-loader'),
// When building for production we extract CSS into
// separate files.
!dev && {
loader: MiniCssExtractPlugin.loader,
options: {},
},
// Resolve CSS `@import`s and `url()`s
{
loader: require.resolve('css-loader'),
options: { importLoaders: 1, sourceMap: !dev },
},
// Compile CSS
{
loader: require.resolve('postcss-loader'),
options: {
ident: 'postcss',
plugins: () => [
// 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: !dev,
},
},
].filter(Boolean),
// A global CSS import always has side effects. Webpack will tree
// shake the CSS without this option if the issuer claims to have
// no side-effects.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
} as webpack.RuleSetRule),
config.experimental.css &&
({
loader: require.resolve('file-loader'),
issuer: {
// file-loader is only used for CSS files, e.g. url() for a SVG
// or font files
test: /\.css$/,
},
// Exclude extensions that webpack handles by default
exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash].[ext]',
},
} as webpack.RuleSetRule),
].filter(Boolean), ].filter(Boolean),
}, },
plugins: [ plugins: [
...@@ -652,6 +750,14 @@ export default async function getBaseWebpackConfig( ...@@ -652,6 +750,14 @@ export default async function getBaseWebpackConfig(
clientManifest: config.experimental.granularChunks, clientManifest: config.experimental.granularChunks,
modern: config.experimental.modern, modern: config.experimental.modern,
}), }),
// Extract CSS as CSS file(s) in the client-side production bundle.
config.experimental.css &&
!isServer &&
!dev &&
new MiniCssExtractPlugin({
filename: 'static/css/[contenthash].css',
chunkFilename: 'static/css/[contenthash].chunk.css',
}),
tracer && tracer &&
new ProfilingPlugin({ new ProfilingPlugin({
tracer, tracer,
......
...@@ -238,10 +238,28 @@ function renderReactElement (reactEl, domEl) { ...@@ -238,10 +238,28 @@ function renderReactElement (reactEl, domEl) {
// The check for `.hydrate` is there to support React alternatives like preact // The check for `.hydrate` is there to support React alternatives like preact
if (isInitialRender) { if (isInitialRender) {
ReactDOM.hydrate(reactEl, domEl, markHydrateComplete) ReactDOM.hydrate(reactEl, domEl, function () {
if (process.env.NODE_ENV !== 'production') {
document
.querySelectorAll('[data-next-hydrating]')
.forEach(function (el) {
el.remove()
})
}
markHydrateComplete()
})
isInitialRender = false isInitialRender = false
} else { } else {
ReactDOM.render(reactEl, domEl, markRenderComplete) ReactDOM.render(reactEl, domEl, function () {
if (process.env.NODE_ENV !== 'production') {
document
.querySelectorAll('[data-next-hydrating]')
.forEach(function (el) {
el.remove()
})
}
markRenderComplete()
})
} }
} }
......
...@@ -140,6 +140,8 @@ export type DocumentProps = DocumentInitialProps & { ...@@ -140,6 +140,8 @@ export type DocumentProps = DocumentInitialProps & {
inAmpMode: boolean inAmpMode: boolean
hybridAmp: boolean hybridAmp: boolean
staticMarkup: boolean staticMarkup: boolean
isDevelopment: boolean
hasCssMode: boolean
devFiles: string[] devFiles: string[]
files: string[] files: string[]
dynamicImports: ManifestItem[] dynamicImports: ManifestItem[]
......
...@@ -40,6 +40,7 @@ const defaultConfig: { [key: string]: any } = { ...@@ -40,6 +40,7 @@ const defaultConfig: { [key: string]: any } = {
(Number(process.env.CIRCLE_NODE_TOTAL) || (Number(process.env.CIRCLE_NODE_TOTAL) ||
(os.cpus() || { length: 1 }).length) - 1 (os.cpus() || { length: 1 }).length) - 1
), ),
css: false,
documentMiddleware: false, documentMiddleware: false,
granularChunks: false, granularChunks: false,
modern: false, modern: false,
......
...@@ -76,6 +76,7 @@ export default class Server { ...@@ -76,6 +76,7 @@ export default class Server {
assetPrefix?: string assetPrefix?: string
canonicalBase: string canonicalBase: string
documentMiddlewareEnabled: boolean documentMiddlewareEnabled: boolean
hasCssMode: boolean
dev?: boolean dev?: boolean
} }
private compression?: Middleware private compression?: Middleware
...@@ -121,6 +122,7 @@ export default class Server { ...@@ -121,6 +122,7 @@ export default class Server {
canonicalBase: this.nextConfig.amp.canonicalBase, canonicalBase: this.nextConfig.amp.canonicalBase,
documentMiddlewareEnabled: this.nextConfig.experimental documentMiddlewareEnabled: this.nextConfig.experimental
.documentMiddleware, .documentMiddleware,
hasCssMode: this.nextConfig.experimental.css,
staticMarkup, staticMarkup,
buildId: this.buildId, buildId: this.buildId,
generateEtags, generateEtags,
......
...@@ -130,6 +130,7 @@ type RenderOpts = { ...@@ -130,6 +130,7 @@ type RenderOpts = {
runtimeConfig?: { [key: string]: any } runtimeConfig?: { [key: string]: any }
dangerousAsPath: string dangerousAsPath: string
assetPrefix?: string assetPrefix?: string
hasCssMode: boolean
err?: Error | null err?: Error | null
autoExport?: boolean autoExport?: boolean
nextExport?: boolean nextExport?: boolean
...@@ -168,6 +169,7 @@ function renderDocument( ...@@ -168,6 +169,7 @@ function renderDocument(
skeleton, skeleton,
dynamicImportsIds, dynamicImportsIds,
dangerousAsPath, dangerousAsPath,
hasCssMode,
err, err,
dev, dev,
ampPath, ampPath,
...@@ -219,6 +221,8 @@ function renderDocument( ...@@ -219,6 +221,8 @@ function renderDocument(
canonicalBase={canonicalBase} canonicalBase={canonicalBase}
ampPath={ampPath} ampPath={ampPath}
inAmpMode={inAmpMode} inAmpMode={inAmpMode}
isDevelopment={!!dev}
hasCssMode={hasCssMode}
hybridAmp={hybridAmp} hybridAmp={hybridAmp}
staticMarkup={staticMarkup} staticMarkup={staticMarkup}
devFiles={devFiles} devFiles={devFiles}
......
...@@ -84,20 +84,28 @@ ...@@ -84,20 +84,28 @@
"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",
"devalue": "2.0.0", "devalue": "2.0.0",
"etag": "1.8.1", "etag": "1.8.1",
"file-loader": "4.2.0",
"find-up": "4.0.0", "find-up": "4.0.0",
"fork-ts-checker-webpack-plugin": "1.3.4", "fork-ts-checker-webpack-plugin": "1.3.4",
"fresh": "0.5.2", "fresh": "0.5.2",
"ignore-loader": "0.1.2",
"is-docker": "2.0.0", "is-docker": "2.0.0",
"jest-worker": "24.9.0", "jest-worker": "24.9.0",
"launch-editor": "2.2.1", "launch-editor": "2.2.1",
"loader-utils": "1.2.3", "loader-utils": "1.2.3",
"mini-css-extract-plugin": "0.8.0",
"mkdirp": "0.5.1", "mkdirp": "0.5.1",
"node-fetch": "2.6.0", "node-fetch": "2.6.0",
"optimize-css-assets-webpack-plugin": "5.0.3",
"ora": "3.4.0", "ora": "3.4.0",
"path-to-regexp": "2.1.0", "path-to-regexp": "2.1.0",
"pnp-webpack-plugin": "1.5.0", "pnp-webpack-plugin": "1.5.0",
"postcss-flexbugs-fixes": "4.1.0",
"postcss-loader": "3.0.0",
"postcss-preset-env": "6.7.0",
"prop-types": "15.7.2", "prop-types": "15.7.2",
"prop-types-exact": "1.2.0", "prop-types-exact": "1.2.0",
"raw-body": "2.4.0", "raw-body": "2.4.0",
...@@ -107,6 +115,7 @@ ...@@ -107,6 +115,7 @@
"source-map": "0.6.1", "source-map": "0.6.1",
"string-hash": "1.1.3", "string-hash": "1.1.3",
"strip-ansi": "5.2.0", "strip-ansi": "5.2.0",
"style-loader": "1.0.0",
"styled-jsx": "3.2.2", "styled-jsx": "3.2.2",
"terser": "4.0.0", "terser": "4.0.0",
"unfetch": "4.1.0", "unfetch": "4.1.0",
...@@ -141,9 +150,11 @@ ...@@ -141,9 +150,11 @@
"@types/find-up": "2.1.1", "@types/find-up": "2.1.1",
"@types/fresh": "0.5.0", "@types/fresh": "0.5.0",
"@types/loader-utils": "1.1.3", "@types/loader-utils": "1.1.3",
"@types/mini-css-extract-plugin": "0.8.0",
"@types/mkdirp": "0.5.2", "@types/mkdirp": "0.5.2",
"@types/nanoid": "2.0.0", "@types/nanoid": "2.0.0",
"@types/node-fetch": "2.3.4", "@types/node-fetch": "2.3.4",
"@types/optimize-css-assets-webpack-plugin": "5.0.0",
"@types/react": "16.8.18", "@types/react": "16.8.18",
"@types/react-dom": "16.8.4", "@types/react-dom": "16.8.4",
"@types/react-is": "16.7.1", "@types/react-is": "16.7.1",
......
...@@ -344,6 +344,25 @@ export class Head extends Component< ...@@ -344,6 +344,25 @@ export class Head extends Component<
return ( return (
<head {...this.props}> <head {...this.props}>
{this.context._documentProps.isDevelopment &&
this.context._documentProps.hasCssMode && (
<>
<style
data-next-hydrating
dangerouslySetInnerHTML={{
__html: `body{-webkit-animation:-next-hydrating 3s steps(1,end) 0s 1 normal both;-moz-animation:-next-hydrating 3s steps(1,end) 0s 1 normal both;-ms-animation:-next-hydrating 3s steps(1,end) 0s 1 normal both;animation:-next-hydrating 3s steps(1,end) 0s 1 normal both}@-webkit-keyframes -next-hydrating{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -next-hydrating{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -next-hydrating{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -next-hydrating{from{visibility:hidden}to{visibility:visible}}@keyframes -next-hydrating{from{visibility:hidden}to{visibility:visible}}`,
}}
/>
<noscript>
<style
data-next-hydrating
dangerouslySetInnerHTML={{
__html: `body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}`,
}}
/>
</noscript>
</>
)}
{children} {children}
{head} {head}
<meta <meta
......
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 className='red-text'>This text should be red.</div>
}
@media (480px <= width < 768px) {
::placeholder {
color: green;
}
}
import React from 'react'
import App from 'next/app'
class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
import '../styles/global.css'
export default function Home () {
return <div className='red-text'>This text should be red.</div>
}
import '../styles/global.css'
export default function Home () {
return <div className='red-text'>This text should be red.</div>
}
import React from 'react'
import App from 'next/app'
import '../styles/global2.css'
import '../styles/global1.css'
class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
export default function Home () {
return <div className='red-text'>This text should be red.</div>
}
import React from 'react'
import App from 'next/app'
import '../styles/global1.css'
import '../styles/global2.css'
class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
export default function Home () {
return <div className='red-text'>This text should be red.</div>
}
import React from 'react'
import App from 'next/app'
import '../styles/global1.css'
import '../styles/global2.css'
class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
import Link from 'next/link'
export default function Page1 () {
return (
<>
<div className='red-text'>This text should be red.</div>
<br />
<input key={'' + Math.random()} id='text-input' type='text' />
<br />
<Link href='/page2'>
<a>Switch page</a>
</Link>
</>
)
}
import Link from 'next/link'
export default function Page2 () {
return (
<>
<div className='blue-text'>This text should be blue.</div>
<br />
<input key={'' + Math.random()} id='text-input' type='text' />
<br />
<Link href='/page1'>
<a>Switch page</a>
</Link>
</>
)
}
import React from 'react'
import App from 'next/app'
import '../styles/global1.css'
import '../styles/global2.css'
class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
export default function Home () {
return <div className='red-text'>This text should be red.</div>
}
@import './global1b.css';
.red-text {
color: red;
}
.red-text {
color: purple;
font-weight: bolder;
}
@import './global2b.css';
.blue-text {
color: blue;
}
.blue-text {
color: orange;
font-weight: bolder;
}
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 className='red-text'>This text should be red.</div>
}
<?xml version="1.0" encoding="UTF-8"?>
<svg width="113px" height="100px" viewBox="0 0 113 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 51.2 (57519) - http://www.bohemiancoding.com/sketch -->
<title>Logotype - White</title>
<desc>Created with Sketch.</desc>
<defs>
<linearGradient x1="196.572434%" y1="228.815483%" x2="50%" y2="50%" id="linearGradient-1">
<stop stop-color="#000000" offset="0%"></stop>
<stop stop-color="#FFFFFF" offset="100%"></stop>
</linearGradient>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="White-Triangle" transform="translate(-294.000000, -150.000000)" fill="url(#linearGradient-1)">
<polygon id="Logotype---White" points="350.5 150 407 250 294 250"></polygon>
</g>
</g>
</svg>
import React from 'react'
import App from 'next/app'
import '../styles/global1.css'
import '../styles/global2.css'
class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
export default function Home () {
return <div className='red-text'>This text should be red.</div>
}
<?xml version="1.0" encoding="UTF-8"?>
<svg width="114px" height="100px" viewBox="0 0 114 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 51.2 (57519) - http://www.bohemiancoding.com/sketch -->
<title>Logotype - Black</title>
<desc>Created with Sketch.</desc>
<defs>
<linearGradient x1="100.929941%" y1="181.283245%" x2="41.7687834%" y2="100%" id="linearGradient-1">
<stop stop-color="#FFFFFF" offset="0%"></stop>
<stop stop-color="#000000" offset="100%"></stop>
</linearGradient>
</defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Black-Triangle" transform="translate(-293.000000, -150.000000)" fill="url(#linearGradient-1)">
<polygon id="Logotype---Black" points="350 150 407 250 293 250"></polygon>
</g>
</g>
</svg>
.red-text {
color: red;
background-image: url('./dark.svg');
}
@import './global2b.css';
.blue-text {
color: blue;
}
.blue-text {
color: orange;
font-weight: bolder;
background-image: url(../assets/light.svg);
}
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
import '../styles/global.css'
export default function Home () {
return <div className='red-text'>This text should be red.</div>
}
module.exports = {
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60
},
experimental: { css: true, granularChunks: true }
}
This diff is collapsed.
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