Ant-design: Remove global Styles

Created on 15 Feb 2018  ·  30Comments  ·  Source: ant-design/ant-design

Version

3.2.1

Environment

Any

Reproduction link

https://codesandbox.io/s/jnw46698m3

Steps to reproduce

1- Import an antd component
2- Observe global styles (h1,h6, selector, ect...)

What is expected?

Component style to be scoped and not affect the rest of the application.

What is actually happening?

When component is imported the entire HTML application (even outside of React) is styled.


This is a response to issue #9362 & #4331

Inactive ❓FAQ

Most helpful comment

Hi there!
I solved this by importing component styles in a different way.

Initially I was importing the styles like this:
import 'antd/lib/button/style/css';

But that css.js not just import button's styles, also import general styles, this is it's content:

"use strict";

// General styling (body, h1, h2..)
require("../../style/index.css");

// Button styles
require("./index.css");

So I solved it by just importing index.css file like this:
import 'antd/lib/button/style/index.css';

All 30 comments

You can also try using components directly from https://github.com/react-component.
antd is built on top of them, and they are unstyled.

Please address this. It's a hard blocker for our app.

Hi, have you guys given thoughts about using a CSS-in-JS library like emotion or styled-components. It could solve lot of problems like global import for styles and scoping the styles to the ant components. Plus it could also improve theming (dynamic styles). Apologies if this has been discussed somewhere else, I couldn't find relevant discussion(s).

@divyanshu013 I think I read it's not a top priority for them as antd is meant to include the antd style specification not just the components/javascript. Plus, this is technically mean to be a monorepo for their internal projects, so themeing for other people's brands is automatically not a top priority. That said, I'm with you, I wish it used styled-components over global styles.

https://github.com/ant-design/ant-design/issues/5570#issuecomment-306960517

https://spectrum.chat/thread/ca82a625-134f-49df-9900-1b0b6342e037

Ok, I must admit I haven't looked at antd's less file structure that deeply, so maybe someone can shed some light on this:

How big an offence is it to simply include only the component's less file? E.g. do something like

import { Select } from 'antd';
import 'antd/lib/select/style/index.less';

Based on a quick test, it seems to work, so that made me curious...
I'm sure this will break with updates, but the other solutions seem to risk it as well.

This is related to being able to import styles for individual components. If the styles for components were self-contained then people could opt-in or opt-out of the global reset/styles.

Situation right now:

  • Removing global resets and styles is not feasible because it would be a breaking change.
  • Importing styles for individual components doesn't currently work because they sometimes have hidden dependencies, and rely on global styles.

How could we make the components self contained in a non-breaking way? I think one solution could be to use Storybook to setup some isolated visual regression tests.

You could generate snapshots with global styles included, then remove the global styles, and add in styles in the component less files until the tests pass, ensuring that the style is the same with or without the global styles.

ref #4331 #13459

_Apologies for creating a semi-duplicate issue. To consolidate conversation, I'll re-ask my somewhat different questions here._

What if the community could do the work to transition component styles to no longer depend on global styles?

One approach (thanks @DylanVann):

  1. Add automated visual regression testing for all components
  2. Refactor component styles to use previously-global styles in a non-global manner
  3. Confirm no breaking changes to components
  4. Offer today's base.less, with global styles, as an opt-in import, for those dependent on it

Is Ant open to:

  1. Reviewing and potentially accepting PR(s) for that work?
  2. Accepting the compromise of providing an opt-in import for those consumers currently relying on the global styles?

Any update?

Hi there!
I solved this by importing component styles in a different way.

Initially I was importing the styles like this:
import 'antd/lib/button/style/css';

But that css.js not just import button's styles, also import general styles, this is it's content:

"use strict";

// General styling (body, h1, h2..)
require("../../style/index.css");

// Button styles
require("./index.css");

So I solved it by just importing index.css file like this:
import 'antd/lib/button/style/index.css';

Nice find!

Are there more complex component that depend on more than one index.css file?
Are there components that would break without the main general styles file?

Nice find!

Thank you 😄

Are there more complex component that depend on more than one index.css file?

Maybe, in that case I would import all the files, I think it wouldn't be too many.

Are there components that would break without the main general styles file?

It worked fine with buttons (the only component I used).
But maybe some components could use those styles, this is something I need to check out.

I do it in the same way as @fedebabrauskas, and everything seems to be working well.

@fedebabrauskas It seems like the animation for the component would not be enabled (I tried Popover, the styles are fine but it has no animation)

Ok, I must admit I haven't looked at antd's less file structure that deeply, so maybe someone can shed some light on this:

How big an offence is it to simply include only the component's less file? E.g. do something like

import { Select } from 'antd';
import 'antd/lib/select/style/index.less';

Based on a quick test, it _seems_ to work, so that made me curious...
I'm sure this will break with updates, but the other solutions seem to risk it as well.

This is a life saver!
I had been using import 'antd/dist/antd.css'; inside the component and that messed the global styles.
Searched on Google and found this issue.
I needed only the styles for switch component so I tried import 'antd/lib/switch/style/index.less'; and boom! it worked!!
Thanks a lot buddy!!
Code implementation
Deployed portfolio

So, just to confirm, as of Today, it is not possible to NOT import index.css ?

I am using Gatbsy, and my global.css is being overwritten by ants index.css.

As a workaroud - I just created a postinstall script like below

scripts/postinstall.js

#!/usr/bin/env node
const replace = require('replace-in-file');

const removeAntdGlobalStyles = () => {
    const options = {
        files: [`${process.cwd()}/node_modules/antd/lib/style/core/index.less`, `${process.cwd()}/node_modules/antd/es/style/core/index.less`],
        from: "@import 'base';",
        to: '',
    };

    replace(options)
        .then(() => {
            console.log('[INFO] Successfully Removed Antd Global Styles:');
        })
        .catch(e => {
            console.error('[ERR] Error removing Antd Global Styles:', e);
            process.exit(1);
        });
};


removeAntdGlobalStyles();

package.json

 "devDependencies": {
  //other dependancies
  "replace-in-file": "^5.0.2"
},
"scripts": {
  // other scripts
  "postinstall": "node scripts/postintall.js"
}

Note: I'm using babel-plugin-import for on-demand component imports

As a workaroud - I just created a postinstall script like below

scripts/postinstall.js

#!/usr/bin/env node
const replace = require('replace-in-file');

const removeAntdGlobalStyles = () => {
    const options = {
        files: [`${process.cwd()}/node_modules/antd/lib/style/core/index.less`, `${process.cwd()}/node_modules/antd/es/style/core/index.less`],
        from: "@import 'base';",
        to: '',
    };

    replace(options)
        .then(() => {
            console.log('[INFO] Successfully Removed Antd Global Styles:');
        })
        .catch(e => {
            console.error('[ERR] Error removing Antd Global Styles:', e);
            process.exit(1);
        });
};

removeAntdGlobalStyles();

package.json

 "devDependencies": {
  //other dependancies
  "replace-in-file": "^5.0.2"
},
"scripts": {
  // other scripts
  "postinstall": "node scripts/postintall.js"
}

The script removes the base styles but still doesn't get rid of global antd styles. Do you import styles for each antd component or a single dist css file.

@himanshuc3 I'm using babel-plugin-import for on-demand component imports

@fedebabrauskas It seems like the animation for the component would not be enabled (I tried Popover, the styles are fine but it has no animation)

same case, but with Collapse

babel-plugin-import imports global styles,
and importing a specific component css file like this :
import 'antd/lib/date-picker/style/index.css';
breaks the Datepicker (it opens and closes itself in weird and unexpected ways.)

Any workaround about that ?

omg i'm using transfer component that relies on many other components... Just realise now that all my dark typography header doesn't follow my primary colors etc etc..

+1

+1

This is a workaround I used on a demo app which uses Ant Design along other component libraries:

index.scss:

.antPage {
  @import '~antd/dist/antd.min';
  ...
}

So now all global styles for Ant are namespaced, and I can just do this on my Ant-styled page:

function AntPage() => <div className="antPage">...</div>

But then I get another problem, since some of the components provided by this library can't really cope with namespaced styles :(

For example the DatePicker renders the markup _outside_ of the body, so the resulting component is not inside .antPage and therefore the styles don't work. Same for dropdowns and other components needing extra markup to work.

Then, if I try the workaround suggested above:

import 'antd/es/date-picker/style/index.css'
import 'antd/es/dropdown/style/index.css'
import 'antd/es/input/style/index.css'

It _almost_ works, but it starts behaving weirdly: when I focus a date picker, it doesn't appear, but instead remains with opacity: 0. Then, as soon as it loses focus, the floating date picker appears... 😕

Not exactly sure how loading the styles separately would affect the behaviour, it might be a different bug.

In any case, let's see if a non-global styles version could do the trick for good :+1:

@OscardR I believe this issue is something to do with not including the motion css files @import 'antd/es/style/core/motion.less'; fixed it for me.

If anyone else has similar issues and wants to import all styles but not have the globals:

I have imported all the .less files and placed them into a antd.less file, then I import that file instead of the dist files which include the global styles.

https://gist.github.com/SPDUK/b93e9c28c11e41d5f3b6d9ad9fc7be36

Do we bave any other option if i'm not a less user? I'm using sass and don't want to add less just to patch this. I would like to be able to load only the minimal css files to execute the Select component

Almost 3 years that I see this issue pop on top of my Github homepage.

I have stopped using ant for a long time now. Can I just close this and let the community or maintainers follow on it elsewhere?

Anything about Remove global Styles, everyone is now focusing on this, please just only unsubscribe this issue if you don't want to know more about it, thank you!

I don't think it's the best idea. A lot of us are still using antd and would love this issue to be resolved.
It's good to have a main issue will all the history.

Was this page helpful?
0 / 5 - 0 ratings