Vite generates multiple copies of the same stylesheet
See original GitHub issueDescribe the bug
I am using the following vite config option to make global styles available in React components without requirement of usage of “@import '…/…/syles/main” in each component file:
css: {
preprocessorOptions: {
scss: {
additionalData: `
@import "./src/styles/main";
`
}
}
}
it comes from https://github.com/vitejs/vite/issues/832
My main.scss looks like:
@import "./node_modules/normalize.css/normalize";
@import 'fonts';
@import 'colors';
@import 'breakpoints';
@import 'animations';
@import 'layers';
where fonts, colors, breakpoints, animations, layers include global variables.
It works fine in part I can use my variables inside component without importing the main SCSS file, but such approach causes an issue that I have multiple copies of the same stylesheet in a head section of page ( see the screenshot: https://imgur.com/a/k6hGnbP )
Reproduction
- Create empty app (Vite, React, TSX)
- Create a global main.scss file
- Import partials _colors.scss and _fonts.scss to main.scss using @import
- Create vite.config.js with option similar to described in a bug description section
- Create at least two different components and add it to your App
- Add some variables to colors.scss and fonts.scss
- Use variables from colors.scss and fonts.scss in your two components from step 5 using build-in CSS modules support ([component].module.scss)
- Run your app and look at head section
Expected result: There is only one global stylesheet. Actual result: There are multiple copies of global stylesheet, where number of copies equals number of unique components,
UPDATE: I’ve created a simplified app which one reproduces the issue: https://github.com/tastytea-github/vite-global-import-issue-reproduction
- Clone repo
- Install deps with npm i
- Run app with npm run dev
- Look at head section of the rendered page in devtools
Expected state: styles from main.scss are added globally only once. Actual state: styles from main.scss are included to each unique component.
System Info
No
Used Package Manager
npm
Logs
No response
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn’t already an issue that reports the same bug to avoid creating a duplicate.
- Make sure this is a Vite issue and not a framework-specific issue. For example, if it’s a Vue SFC related bug, it should likely be reported to https://github.com/vuejs/vue-next instead.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:12
- Comments:28 (5 by maintainers)
@patak-js Hello sir. Could you be so kind to pay attention to this issue?
feat: css
means the issue is related to the CSS bundling feature of Vite. It’s not indicating that it is a feature request.