Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove global Styles #9363

Closed
raed667 opened this issue Feb 15, 2018 · 58 comments
Closed

Remove global Styles #9363

raed667 opened this issue Feb 15, 2018 · 58 comments
Labels
❓FAQ issues would be discussed a lot Inactive

Comments

@raed667
Copy link

raed667 commented Feb 15, 2018

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

@zachguo
Copy link
Contributor

zachguo commented Mar 29, 2018

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

@jclif
Copy link

jclif commented Jul 21, 2018

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

@divyanshu013
Copy link

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).

@acomito
Copy link

acomito commented Aug 11, 2018

@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.

#5570 (comment)

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

@scleikas
Copy link

scleikas commented Oct 2, 2018

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.

@DylanVann
Copy link

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.

@afc163
Copy link
Member

afc163 commented Dec 6, 2018

ref #4331 #13459

@kylegach
Copy link

kylegach commented Dec 6, 2018

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?

@xcv58
Copy link

xcv58 commented Mar 17, 2019

Any update?

@fedebabrauskas

This comment has been minimized.

@raed667
Copy link
Author

raed667 commented May 9, 2019

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?

@blyszcz
Copy link

blyszcz commented May 18, 2019

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

@harrisonlo
Copy link

@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)

@adibsadeghi1993
Copy link

adibsadeghi1993 commented Oct 10, 2021

import 'antd/lib/TimePicker/style/index.less timepicker is undefinded how solve this problem

@Webbrother
Copy link

@phibersoft
As far as I understand your idea you exclude global.less from import. Am I right?
If so, do you have any issues with that global style, and how do you solve them?

@adibsadeghi1993
Copy link

adibsadeghi1993 commented Oct 11, 2021 via email

@undfndusr
Copy link

undfndusr commented Jan 19, 2022

Another option with webpack:
Install the babel-plugin-import, and configure it this way:

{
    test: /\.jsx$/,
    use: {
        loader: 'babel-loader',
        options: {
            plugins: [
                [
                    'import',
                    {
                        libraryName: 'antd',
                        libraryDirectory: 'es',
                        // `name` argument looks like `{libraryName}/{libraryDirectory}/{componentName}`
                        style: (name: string) => {
                            // exclude components without index.css file, e.g. `col` and `row` from `table`
                            return ['antd/es/row', 'antd/es/col'].includes(name)
                                ? false
                                : `${name}/style/index.css`;
                        },
                    },
                ],
            ],
        },
    },
}

You need to import {antComponentName}/style/index.css instead {antComponentName}/style/index.less or {antComponentName}/style/index.js files because .css not imports core and reset styles.

More info in plugin docs.

@ankitsingh808
Copy link

So I ran into this same issue
I am importing components like this:

import Breadcrumb from 'antd/lib/breadcrumb'
import 'antd/lib/breadcrumb/style/index.css' 

But after making the build, I found global.less file is over-riding the whole page

@yashsway
Copy link

yashsway commented Jul 28, 2022

There needs to be a bundled option in dist/ to get all the component styles without the global styles in it. This is still an issue!

@yashsway
Copy link

After hours of research and testing, I've finally found a solution that works. I tried both the NormalModuleReplacementPlugin and IgnorePlugin and neither worked.

Added the following to my craco config under webpack (In vanilla Webpack, this will go under the resolve property):

alias: {
    [path.resolve(__dirname, '../../node_modules/antd/lib/style/index.less')]: path.resolve(__dirname, "src/assets/styles/antd.less")
}

Folder structure:

.
└── monorepo_root/
    ├── node_modules/
    │   └── antd/
    │       └── lib/
    │           └── style/
    │               ├── core/
    │               │   └── global.less (problematic file. This is imported in index.less)
    │               └── index.less
    └── apps/
        ├── my_cra_app/
        │   ├── node_modules/
        │   └── (craco running here!)
        └── src/
            └── assets/
                └── styles/
                    └── antd.less

Contents of antd.less (as found in https://ant.design/docs/react/customize-theme#How-to-avoid-modifying-global-styles):

#antd {
  @import '~antd/es/style/core/index.less';
  @import '~antd/es/style/themes/default.less';
}

NOTE: this is a solution for Webpack 5.
References:
Webpack Ignore Plugin - https://webpack.js.org/plugins/ignore-plugin/
Webpack Normal Module Replacement Plugin - https://webpack.js.org/plugins/normal-module-replacement-plugin/
Webpack Resolve Alias - https://webpack.js.org/configuration/resolve/#resolvealias
Craco - https://github.com/dilanx/craco/blob/master/packages/craco/README.md

@PaperTiger7
Copy link

In my case, I partially solved the problem copying ../antd/dist/antd.css to other folder, and deleting all classes except the necessary classes for my components. I also minified it to reduce its size.
I opened a question on Stack Overflow in spanish proposing this solution: Remover estilos globales de Ant Design sin perder la funcionalidad de sus componentes.

Can you share the modified file please?

I could share it with you but I have it in a private repository.

Anyway, the key would be to remove all the unnecessary styles and leave only the ones that your AntDesign components need.

The file is ../antd/dist/antd.css .

I also faced this problem.Can you share the modified antd file please?Thank you ,my email is 876530150@qq.com

@OnurGvnc
Copy link

I'm not sure if there are any side effects. but i solved it like this;

next.config.js or vite.config.js or webpack.config.js

const fs = require('fs')
fs.writeFileSync(require.resolve('antd/es/style/core/global.less'), '')
fs.writeFileSync(require.resolve('antd/lib/style/core/global.less'), '')

@malyanoff
Copy link

After hours of research and testing, I've finally found a solution that works. I tried both the NormalModuleReplacementPlugin and IgnorePlugin and neither worked.

Added the following to my craco config under webpack (In vanilla Webpack, this will go under the resolve property):

alias: {
    [path.resolve(__dirname, '../../node_modules/antd/lib/style/index.less')]: path.resolve(__dirname, "src/assets/styles/antd.less")
}

Folder structure:

.
└── monorepo_root/
    ├── node_modules/
    │   └── antd/
    │       └── lib/
    │           └── style/
    │               ├── core/
    │               │   └── global.less (problematic file. This is imported in index.less)
    │               └── index.less
    └── apps/
        ├── my_cra_app/
        │   ├── node_modules/
        │   └── (craco running here!)
        └── src/
            └── assets/
                └── styles/
                    └── antd.less

Contents of antd.less (as found in https://ant.design/docs/react/customize-theme#How-to-avoid-modifying-global-styles):

#antd {
  @import '~antd/es/style/core/index.less';
  @import '~antd/es/style/themes/default.less';
}

NOTE: this is a solution for Webpack 5. References: Webpack Ignore Plugin - https://webpack.js.org/plugins/ignore-plugin/ Webpack Normal Module Replacement Plugin - https://webpack.js.org/plugins/normal-module-replacement-plugin/ Webpack Resolve Alias - https://webpack.js.org/configuration/resolve/#resolvealias Craco - https://github.com/dilanx/craco/blob/master/packages/craco/README.md

Can you show me the whole craco.config.js?

@rahulbansal16
Copy link

Is there an official fix for it? I have created a content-script in my chrome extension that is making changes to the dom, the antd import statement is affecting the global styles.

@joker77877
Copy link

Is there an official fix for it?

@csr632
Copy link
Contributor

csr632 commented Oct 19, 2022

I have created a simple less plugin to solve this issue: less-plugin-remove-antd-global-styles. It works by mapping the global.less into an empty file. It works well with vite, webpack, rollup and babel-plugin-import.

// webpack.config.js
const { LessPluginRemoveAntdGlobalStyles } = require('less-plugin-remove-antd-global-styles');

module.exports = {
  ...
    {
      loader: 'less-loader',
      options: {
        lessOptions: {
          plugins: [
            new LessPluginRemoveAntdGlobalStyles(),
          ],
        },
      },
    },
  ...
};

Checkout its README for more usage.

@rkuykendall
Copy link

Can we close this issue with the release of Ant 5? If not, what needs to be done?

🎉

@afc163 afc163 closed this as completed Dec 19, 2022
@raed667
Copy link
Author

raed667 commented Jan 31, 2023

OMG !!! I can't believe it ❤️ we can finally put this issue to rest ...

image

@hanwenbo
Copy link

hanwenbo commented Feb 24, 2023

这两种写法都可以

下面的替换成一个新建的空文件即可

chainWebpack(config, {env, webpack, createCSSRule}) {
    // const fs = require('fs')
    // fs.writeFileSync(require.resolve('antd/es/style/core/global.less'), '')
    // fs.writeFileSync(require.resolve('antd/lib/style/core/global.less'), '')
    // 添加NormalModuleReplacementPlugin
    config
      .plugin('normalModuleReplacement')
      .use(webpack.NormalModuleReplacementPlugin, [
        // 匹配需要替换的模块路径
        /antd\/es\/style\/core\/global.less/,
        // 替换成的模块路径或实现
        path.resolve(__dirname, './antd/global.less')
      ])
      .use(webpack.NormalModuleReplacementPlugin, [
        // 匹配需要替换的模块路径
        /antd\/es\/style\/lib\/global.less/,
        // 替换成的模块路径或实现
        path.resolve(__dirname, './antd/global.less')
      ])
  },

@shongs27
Copy link

shongs27 commented Aug 18, 2023

@afc163

I wonder how this problem was solved. (any related PR?)
I read from the top. As far as I understand, the problem seems to have been solved by modifying from '.less' to 'css-in-js'. Is that right?

@Lucien-X
Copy link

I have created a simple less plugin to solve this issue: less-plugin-remove-antd-global-styles. It works by mapping the global.less into an empty file. It works well with vite, webpack, rollup and babel-plugin-import.

// webpack.config.js
const { LessPluginRemoveAntdGlobalStyles } = require('less-plugin-remove-antd-global-styles');

module.exports = {
  ...
    {
      loader: 'less-loader',
      options: {
        lessOptions: {
          plugins: [
            new LessPluginRemoveAntdGlobalStyles(),
          ],
        },
      },
    },
  ...
};

Checkout its README for more usage.

thanks alot, that plugin saved my day

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
❓FAQ issues would be discussed a lot Inactive
Projects
None yet
Development

No branches or pull requests