Unverified Commit 1ea67451 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Importing CSS from Third Party React Components (#16993)

parent 5aed1d2e
...@@ -52,7 +52,47 @@ In production, all CSS files will be automatically concatenated into a single mi ...@@ -52,7 +52,47 @@ In production, all CSS files will be automatically concatenated into a single mi
### Import styles from `node_modules` ### Import styles from `node_modules`
If you’d like to import CSS files from `node_modules`, you must do so inside `pages/_app.js`. Importing a CSS file from `node_modules` is permitted in anywhere your application.
For global stylesheets, like `bootstrap` or `nprogress`, you should import the file inside `pages/_app.js`.
For example:
```jsx
// pages/_app.js
import 'bootstrap/dist/css/bootstrap.css'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
```
For importing CSS required by a third party component, you can do so in your component. For example:
```tsx
// components/ExampleDialog.js
import { useState } from 'react'
import { Dialog } from '@reach/dialog'
import '@reach/dialog/styles.css'
function ExampleDialog(props) {
const [showDialog, setShowDialog] = useState(false)
const open = () => setShowDialog(true)
const close = () => setShowDialog(false)
return (
<div>
<button onClick={open}>Open Dialog</button>
<Dialog isOpen={showDialog} onDismiss={close}>
<button className="close-button" onClick={close}>
<VisuallyHidden>Close</VisuallyHidden>
<span aria-hidden>×</span>
</button>
<p>Hello there. I am a dialog</p>
</Dialog>
</div>
)
}
```
## Adding Component-Level CSS ## Adding Component-Level CSS
......
...@@ -154,7 +154,7 @@ export const css = curry(async function css( ...@@ -154,7 +154,7 @@ export const css = curry(async function css(
loader({ loader({
oneOf: [ oneOf: [
{ {
test: [regexCssModules, regexSassModules].filter(Boolean), test: [regexCssModules, regexSassModules],
use: { use: {
loader: 'error-loader', loader: 'error-loader',
options: { options: {
...@@ -171,13 +171,13 @@ export const css = curry(async function css( ...@@ -171,13 +171,13 @@ export const css = curry(async function css(
loader({ loader({
oneOf: [ oneOf: [
{ {
test: [regexCssGlobal, regexSassGlobal].filter(Boolean), test: [regexCssGlobal, regexSassGlobal],
use: require.resolve('next/dist/compiled/ignore-loader'), use: require.resolve('next/dist/compiled/ignore-loader'),
}, },
], ],
}) })
) )
} else if (ctx.customAppFile) { } else {
fns.push( fns.push(
loader({ loader({
oneOf: [ oneOf: [
...@@ -188,28 +188,59 @@ export const css = curry(async function css( ...@@ -188,28 +188,59 @@ export const css = curry(async function css(
// See https://github.com/webpack/webpack/issues/6571 // See https://github.com/webpack/webpack/issues/6571
sideEffects: true, sideEffects: true,
test: regexCssGlobal, test: regexCssGlobal,
issuer: { and: [ctx.customAppFile] }, // We only allow Global CSS to be imported anywhere in the
// application if it comes from node_modules. This is a best-effort
// heuristic that makes a safety trade-off for better
// interoperability with npm packages that require CSS. Without
// this ability, the component's CSS would have to be included for
// the entire app instead of specific page where it's required.
include: { and: [/node_modules/] },
// Global CSS is only supported in the user's application, not in
// node_modules.
issuer: {
and: [ctx.rootDirectory],
not: [/node_modules/],
},
use: getGlobalCssLoader(ctx, postCssPlugins), use: getGlobalCssLoader(ctx, postCssPlugins),
}, },
], ],
}) })
) )
fns.push(
loader({ if (ctx.customAppFile) {
oneOf: [ fns.push(
{ loader({
// A global Sass import always has side effects. Webpack will tree oneOf: [
// shake the Sass without this option if the issuer claims to have {
// no side-effects. // A global CSS import always has side effects. Webpack will tree
// See https://github.com/webpack/webpack/issues/6571 // shake the CSS without this option if the issuer claims to have
sideEffects: true, // no side-effects.
test: regexSassGlobal, // See https://github.com/webpack/webpack/issues/6571
issuer: { and: [ctx.customAppFile] }, sideEffects: true,
use: getGlobalCssLoader(ctx, postCssPlugins, sassPreprocessors), test: regexCssGlobal,
}, issuer: { and: [ctx.customAppFile] },
], use: getGlobalCssLoader(ctx, postCssPlugins),
}) },
) ],
})
)
fns.push(
loader({
oneOf: [
{
// A global Sass import always has side effects. Webpack will tree
// shake the Sass without this option if the issuer claims to have
// no side-effects.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
test: regexSassGlobal,
issuer: { and: [ctx.customAppFile] },
use: getGlobalCssLoader(ctx, postCssPlugins, sassPreprocessors),
},
],
})
)
}
} }
// Throw an error for Global CSS used inside of `node_modules` // Throw an error for Global CSS used inside of `node_modules`
...@@ -217,7 +248,7 @@ export const css = curry(async function css( ...@@ -217,7 +248,7 @@ export const css = curry(async function css(
loader({ loader({
oneOf: [ oneOf: [
{ {
test: [regexCssGlobal, regexSassGlobal].filter(Boolean), test: [regexCssGlobal, regexSassGlobal],
issuer: { and: [/node_modules/] }, issuer: { and: [/node_modules/] },
use: { use: {
loader: 'error-loader', loader: 'error-loader',
...@@ -235,7 +266,7 @@ export const css = curry(async function css( ...@@ -235,7 +266,7 @@ export const css = curry(async function css(
loader({ loader({
oneOf: [ oneOf: [
{ {
test: [regexCssGlobal, regexSassGlobal].filter(Boolean), test: [regexCssGlobal, regexSassGlobal],
use: { use: {
loader: 'error-loader', loader: 'error-loader',
options: { options: {
...@@ -294,7 +325,7 @@ export const css = curry(async function css( ...@@ -294,7 +325,7 @@ export const css = curry(async function css(
// selector), this assumption is required to code-split CSS. // selector), this assumption is required to code-split CSS.
// //
// If this warning were to trigger, it'd be unactionable by the user, // If this warning were to trigger, it'd be unactionable by the user,
// but also not valid -- so we disable it. // but likely not valid -- so we disable it.
ignoreOrder: true, ignoreOrder: true,
}) })
) )
......
import 'example/index.css'
function Home() {
return <div className="red-text">This should be red text.</div>
}
export default Home
...@@ -287,6 +287,35 @@ describe('CSS Support', () => { ...@@ -287,6 +287,35 @@ describe('CSS Support', () => {
}) })
}) })
describe('Valid Global CSS from npm', () => {
const appDir = join(fixturesDir, 'import-global-from-module')
beforeAll(async () => {
await remove(join(appDir, '.next'))
})
it('should compile successfully', async () => {
const { code, stdout } = await nextBuild(appDir, [], {
stdout: true,
})
expect(code).toBe(0)
expect(stdout).toMatch(/Compiled successfully/)
})
it(`should've emitted a single CSS file`, 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(`".red-text{color:\\"red\\"}"`)
})
})
describe('Invalid Global CSS with Custom App', () => { describe('Invalid Global CSS with Custom App', () => {
const appDir = join(fixturesDir, 'invalid-global-with-app') const appDir = join(fixturesDir, 'invalid-global-with-app')
......
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