Skip to content
1

RFC: Importing CSS from Third Party React Components #15208

Timer started this conversation in Ideas
RFC: Importing CSS from Third Party React Components #15208
166d ago · 37 comments

RFC: Importing CSS from Third Party React Components

Background

Next.js currently (as of July 2020) supports two methods of CSS imports:

  1. Global CSS: Imports of Global CSS (e.g. CSS resets, themes) are restricted to an application's Custom <App> to avoid issues arising from ordering—importing Global CSS anywhere in your application would yield nondeterministic computed CSS styles based on the order you navigate through the application.
  2. CSS Modules: Imports of "component-level" CSS (imported anywhere in the application) can be accomplished via CSS Modules. This prevents most nondeterminism issues, but doesn't completely eliminate them (best-effort). Its main purpose is to prevent a child-component from accidentally applying styles to a global selector like div (affecting the entire application).

Use Case

Neither solution outlined above adequately solves for the use case of importing CSS from a third party component/library.

For example, using @reach/slider requires you import @reach/slider/styles.css.

Importing this file as Global CSS would increase the initial load size of every page in your application, even if the component is only used on a single page.

Importing this file as a CSS Module is not an option as the library would not understand having its classnames transformed into local versions.

Proposal

Next.js should allow safely importing third-party/vendor CSS anywhere in the application.

Before we discuss a proposal, let's look at the current two ways CSS can be imported in a Next.js application:

// This imports a file with global side effects, so it is only permitted in
// pages/_app.js.
// This allows selectors like "div { }" etc.
import "./css-reset.css";

// This imports a CSS Module file and exposes all of the class names in the
// `styles` object.
// Selectors like `.foo` in the CSS file must be referenced like `styles.foo`
// in first-party JavaScript.
import styles from "./Button.module.css";

For the @reach/slider use case, we'd want to be able to import @reach/slider/styles.css in an arbitrarily nested component file. This prevents it from being included on pages without a slider!

Due to the global CSS safeguards defined in Background, we cannot make the following "just work" in an arbitrarily nested component file:

import "@reach/slider/styles.css";

Since 3rd-party CSS is out of your control, it must be scoped to prevent it from having global side effects in your application. Thus, we propose the following import style:

import { className } from "@reach/slider/styles.css";

// or

import { className as sliderClassName } from "@reach/slider/styles.css";

This import style makes it clear and explicit that you're importing the 3rd party CSS with a framework-generated prefix, safely containing it from having side-effects in other parts of your application.

To use the vendor CSS, include the class name somewhere in the parent DOM:

import { Slider } from "@reach/slider";
import { className } from "@reach/slider/styles.css";

function Example1() {
  return (
    <div className={className}>
      <Slider min={0} max={200} step={10} />
    </div>
  );
}

function Example2() {
  return <Slider className={className} min={0} max={200} step={10} />;
}

Technical Details

This feature applies prefixing to the imported CSS selectors instead of transforming them into local, let's look at a code example to understand how it works:

Input CSS

/* input.css */
div {
  background-color: blue;
}

.button {
  font-weight: bolder;
}

Usage in JavaScript

import { className } from "./input.css";

className; // => 'input-XXX'

Transformed Input (what's bundled)

/* input.css (transformed) */
.input-XXX div {
  background-color: blue;
}

.input-XXX .button {
  font-weight: bolder;
}

Replies

37 comments

0

@Timer this is a brilliant idea.

import { Slider } from "@reach/slider";
import { className } from "@reach/slider/styles.css";

function Example1() {
  return (
    <div className={className}>
      <Slider min={0} max={200} step={10} />
    </div>
  );
}

function Example2() {
  return <Slider className={className} min={0} max={200} step={10} />;
}

I have no complaints or issues with approach. Let's go 🚀 .

3 replies
@arunoda

@Timer

function Example2() {
  return <Slider className={className} min={0} max={200} step={10} />;
}

Above only works, if only the component supports asking for a className right?

@sergiodxa

I think that is the case when you wrap it in another element above the third-party component so you can load the styles.

@Janpot

Janpot 166d ago
Collaborator

Above only works, if only the component supports asking for a className right?

I think that would also require compiling to

/* input.css (transformed) */
.input-XXX div, div.input-XXX {
  background-color: blue;
}

.input-XXX .button, .button.input-XXX {
  font-weight: bolder;
}

so that any class on the top level element is applied as well.

0

The idea of adding an upper boundary is nice and would definitely work for 3rd party components that are leaf nodes eg. a Slider. However it might not work as nicely for components that accept bigger subtrees as children eg. a Modal dialog.

I think that this is a decent trade-off and probably I wouldn't go further and overthink it!

That said if you want a bullet-proof solution you might want explore the idea of using a custom pragma that would add a scoped class to every JSX element of the 3rd parties component. Something like this https://codesandbox.io/s/k0ymm401zo but better engineered and prod ready. I think that this could be done with a webpack loader. The approach is very similar to styled-jsx's.

4 replies
@giuseppeg

Another case to consider is when components have side effects e.g. a modal component is open and adds a class to body to prevent scrolling (overflow: hidden):

<body class="modal-open">
  <div className={className}>
    <Modal isOpen={true} />
  </div>
</body>

and

/* modal.css (transformed) */
.modal-XXX .modal-open { overflow: hidden } /* this won't match any element */

In this case even my suggestion above would not work. With that I am not suggesting that you should fix all these issues, I am just posting them as they come to mind.

@pacocoursey

pacocoursey 159d ago
Maintainer

Strongly agree that global selectors that will break with a className prefix. There needs to be an escape hatch to support this.

@justincy

That sounds tough. You can't require 3rd party developers to denote which selectors are global; that'd be a non-starter. So Next.js apps would have to know which styles of their libs are global and have some way of informing Next; also tough but more realistic.

0

alternative syntax idea - <style jsx src="@reach/slider/styles.css" />

but i like that you are solving this!

2 replies
@arso1er

While I like that syntax, wouldn't this unecessarily increase bundle size for those not using styled-jsx?

@sw-yx

by how much are we talking? if it's under 3kb I'm fine w it. of course, I'd much prefer if styled-jsx had a static export option.

0

@Timer Thanks for tackling this. One thing to consider here are complex components (like calendars/datepickers) that simply expect a CSS to be imported and don’t expose style props or class names as props. What would be the best way to solve for that?

0 replies
0

I like that you're thinking about this. I still feel like it's a lot to ask application authors to import the css for a library separately from the JS. That's an implementation detail of the library. Importing a component should come with the CSS automatically if it's imported by the library. Next.js is the only tool I know of where that's not true. Especially if it must to be done in the application root, it seems like it would be easy to get out of sync with what components you're actually using in your app (e.g. if you remove one from some page, you have to remember to also remove the CSS from the root?).

This is one of the first issues people ran into when trying out react-spectrum in Next.js. In our case, we use CSS modules during development, but precompile them to global CSS to publish to npm. This works well with most tools, which treat CSS imports as global by default (e.g. CRA, Parcel, webpack with css-loader, etc.). I don't think I'd expect uncompiled CSS modules to work inside node_modules. If libraries publish global CSS that's not scoped somehow (e.g. by using CSS modules to build it, or something like BEM) then that's on them. 🤷

Is there a technical reason why Next.js works differently from other tools, or just a philosophical one?

16 replies
@pacocoursey

pacocoursey 165d ago
Maintainer

I don't think I'd expect uncompiled CSS modules to work inside node_modules

That's not the goal of this RFC (though I guess it could be done?) Next.js should support importing any arbitrary CSS – uncompiled CSS modules could work if it's using vanilla features, or it could throw an error if using features like composes.

Is there a technical reason why Next.js works differently from other tools

I don't have the technical insight to fully answer this, but the section in the background explains why Next.js ensures imported CSS is global in _app:

Imports of Global CSS (e.g. CSS resets, themes) are restricted to an application's Custom <App> to avoid issues arising from ordering—importing Global CSS anywhere in your application would yield nondeterministic computed CSS styles based on the order you navigate through the application

The workaround for this non-determinism is ensuring all 3rd party CSS is "locally scoped" based on the file it's used in.

@devongovett

I don't think it's realistic to force all third party libraries to support being used this way. There are many libraries already out there that import the CSS they need, and which already handle different orders they can be imported themselves. I would guess that most components that import CSS are designed such that the CSS is loaded together with the JS. And scoping your library CSS is just good practice. I don't think it should be up to Next.js to handle that. Library authors should be able to do so, and already need to do so for all other tools they support anyway. Seems like a great feature for application CSS, but for node_modules, I think it should be up to the library author.

0

100% agree with @devongovett points. On a related note, another RFC that was similar to this was requested back in may and there was some good? discussion within it. While this RFC attempts to expand imports to an agnostic .css file extension, I still hold the same sentiments as before.

Summary

1.) Most third party libraries don't use local (module) css in production because the CSS is shared across different components. For example, Ant design's Table uses styles from various other components (Button, Radio, Checkbox, ...etc) . Therefore, if a developer were to use a Table and a Dropdown component separately but within the same page, then they'll essentially be using duplicated CSS (one scoped to a Dropdown as a child to a Table and the other scoped to a Dropdown being its own parent). Which, unfortunately means larger production assets.

2.) If the class names use dynamically generated localIdentNames, then it becomes harder for a developer to override 3rd party styles without using additional DOM markup (like using id to override a style). In addition, if a developer wishes to override these styles via a local/global stylesheet, then the import order (as of now) still isn't guaranteed and there still may be inconsistencies in the UI upon on page load.

3.) When it comes to component reusability, this RFC requires a different mental approach to importing components that most developers most likely won't be aware of. For example, the standard approach to import a 3rd party component is to (where CSS is imported by the package/a babel plugin or manually imported globally):

File 1:

import { Table } from "antd";

...etc
<Table> ...</Table>

File 2:

import { Table } from "antd";

...etc
<Table>...</Table>

While this RFC preaches...

File 1:

import { Table } from "antd";
import { className } from "antd/table/styles.css";

const StyledTable = ({ children }) => (
  <Table className={className}>
    {children}
  </Table>
);

export default StyledTable;

File 2:

import Table from "../components/Table";

...etc
<Table>...</Table>

File 3:

import Table from "../components/Table";

...etc
<Table>...</Table>

While this reusability approach may seem incredibly arbitrary to some more experienced developers, you can bet most developers will not be aware of this Next limitation. It's not really a standard practice by other boilerplates (like the create-react-app) to require this import stylesheet granularity.

Closing Thoughts

As I mentioned in the previous RFC, this has very limited usage as of now. Most UI libraries expect their CSS to be globally imported. Therefore, this RFC may only cover a rather small percentage of libraries that support exporting CSS modules -- as for other libraries adopting this framework... eh... it's a big ask for a maintainer to refactor their entire library for a Next-specific limitation. While I'm not against the feature's implementation, it just seems like another work-around to a bigger problem: Not being able to import/override 3rd party CSS reliably within Next; and when it comes to wide-spread coverage/usage with what has already been published... it just seems too limited.


You might say, this should be covered with proper QA and UI testing setup. But frankly, I don't think everyone use such a sophisticated QA/ UI testing setup, which can detect each and every UI changes.

This is what I'm talking about:

  1. Import a React component for a functionality in the dashboard
  2. It imports global CSS and it does not use CSS modules or similar
  3. Everything looks decent
  4. Ships the app
  5. Then the team ship more commits
  6. After 2 hours the sales team is worry. We are not getting any new sales
  7. After 10 hours of debugging, it found our that this global CSS import has a style which hides the credit card UI in the billing page

So, what Next.js is trying to do what any responsible framework should handle these issues. It's not a technical limitation or lazyness, but trying to be responsible.

@arunoda That scenario should fall upon you (or your team), not upon Next. Next isn't responsible for your project's UI/UX. If some part of the UI doesn't function as a result of your code, then that's on you. I know there's a general push-back from most developers about QA, but if your project generates sales, then you darn-well better protect them by creating/running E2E tests to make sure your project functions as expected in production. I mean, come on! Look how well it's working out for Microsoft when they dumped their QA security patch team to save a few bucks: Article, Article! Yikes, man! 😬

2 replies
@justincy
  1. The issue of duplicate CSS is very valid. But the feature could easily be implemented in a smart way to avoid the duplication by sharing the same generated prefix across all usages in the app.

  2. The className is a just a prefix. Styles can still be easily overridden globally. See #15208 (reply in thread)

  3. Perhaps I don't understand the point you're trying to make. It sounds like you're saying that a developer only needs to import 3rd party CSS once even if the 3rd party package is used multiple times. I believe this is incorrect. You would want to import the CSS every time you want it applied because the CSS isn't imported globally. If we can avoid duplication (as discussed in your first point) then this shouldn't be a problem.

@mattcarlotta
  1. The issue of duplicate CSS is very valid. But the feature could easily be implemented in a smart way to avoid the duplication by sharing the same generated prefix across all usages in the app.

I don't think this is a viable option, especially if the CSS files are separate. Next would have to compare every class name to any previous prefixed CSS and determine whether or not they're unique strings that deserve their own unique prefix or are shared strings that require a previously used prefix. This sounds like a caching nightmare and I'd presume would be very slow and ineffective.

  1. Perhaps I don't understand the point you're trying to make. It sounds like you're saying that a developer only needs to import 3rd party CSS once even if the 3rd party package is used multiple times. I believe this is incorrect. You would want to import the CSS every time you want it applied because the CSS isn't imported globally. If we can avoid duplication (as discussed in your first point) then this shouldn't be a problem.

I think you misunderstood my 3rd point as what you've described is exactly what it's trying to illustrate:

Even if the prefixes are the same, the CSS is still being applied locally (to a file). Therefore, if you want to reuse the component, then you would have to reimport the CSS. Meaning, if your index page uses a 3rd party Button and your about page uses the same third party button, then unless you're reimporting the CSS, the Button is unstyled. Something like the example below is an atypical requirement in current development practices (for 3rd party elements):

pages/index.js

import { Button } from "antd";
import { classNames } from "antd/button";

<Button 
  className={classNames} 
  onClick={() => alert("Hi")}
>
  Hi
</Button>

pages/about.js

import { Button } from "antd";
import { classNames } from "antd/button";

<Button 
  className={classNames} 
  onClick={() => alert("Bye")}
>
  Bye
</Button>

The work-around would be to do what I've mentioned in item 3 -- importing the third party item + CSS into a single project file and then importing that file instead of the third party package. Again, trivial, but not really a standard.

  1. The className is a just a prefix. Styles can still be easily overridden globally. See #15208 (reply in thread)

If I'm not mistaken, the idea is to keep the styles locally scoped to avoid global class name collisions and any potential side-effects:

Its main purpose is to prevent a child-component from accidentally applying styles to a global selector like div (affecting the entire application).

In addition, globally styling a local class goes against the pure environment (guaranteed side-effect free) that Next is trying to establish.

0

safely containing it from having side-effects

This is my main concern - is this worth it? Is it Next.js' responsibility to do this? Right now Next.js does nothing to protect against these side-effects with styled-jsx:

// side-effect-comp.js
const SideEffectComp = () => (
  <div>
    hi
    <style jsx global>{`body { background: red; }`}</style>
  </div>
)

// page.js
const Page = () => (
  <SideEffectComp />
)

Which is equivalent to importing unscoped CSS on a per-component basis:

// side-effect-comp.js
import './side-effect-comp.css'

const SideEffectComp = () => (
  <div>
    hi
  </div>
)

// page.js
const Page = () => (
  <SideEffectComp />
)

As Giuseppe pointed out, prefixing with className potentially breaks 3rd party CSS, which seems like a non-starter, so there must be a way to support unscoped CSS in some way.

0 replies
0

The RFC states:

Since 3rd-party CSS is out of your control, it must be scoped to prevent it from having global side effects in your application.

The previous RFC for enhanced CSS support stated something similar:

Next.js will only allow you to import Global CSS within a custom pages/_app.js.

This is a very important distinction (and a design flaw in other frameworks), as allowing Global CSS to be imported anywhere in your application means nothing could be code-split due to the cascading nature of CSS.

This is an intentional constraint. Because when global CSS is imported in for example, a component, it will behave different when moving from one page to another.

I feel like this needs to be explained. Why does Next.js feel compelled to protect us from this? Are there situations where this is unavoidable? As a developer, it feels like dealing with this ought to be my job, not yours. I should be careful about what CSS I bring in. I should be capable of avoiding conflicts with global 3rd party CSS.

I'm not against this current proposal. It sounds pretty nice if we can get it working. I just want to understand how we got here.

Perhaps we can have both: scoped 3rd party CSS for most situations, unscoped 3rd party CSS for complex situations (like portals).

0 replies
0

How about supporting dynamic import in pages/_app.js and let all imports still be on <App> but remove unused imports dynamically for each page request. Not sure if thats even possible.

0 replies
0

@Timer Timer 109d ago
Maintainer Author

See pull request here: #16993

0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
💡
Ideas
Beta
You can’t perform that action at this time.