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

Vite generates multiple copies of the same stylesheet #4448

Closed
6 tasks done
ghost opened this issue Jul 30, 2021 · 33 comments · Fixed by #12716
Closed
6 tasks done

Vite generates multiple copies of the same stylesheet #4448

ghost opened this issue Jul 30, 2021 · 33 comments · Fixed by #12716

Comments

@ghost
Copy link

ghost commented Jul 30, 2021

Describe 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 #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

  1. Create empty app (Vite, React, TSX)
  2. Create a global main.scss file
  3. Import partials _colors.scss and _fonts.scss to main.scss using @import
  4. Create vite.config.js with option similar to described in a bug description section
  5. Create at least two different components and add it to your App
  6. Add some variables to colors.scss and fonts.scss
  7. Use variables from colors.scss and fonts.scss in your two components from step 5 using build-in CSS modules support ([component].module.scss)
  8. 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

  1. Clone repo
  2. Install deps with npm i
  3. Run app with npm run dev
  4. 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

@ghost ghost added the pending triage label Jul 30, 2021
@akrabdev
Copy link

This may help with this issue:

vite/src/client/client.ts

Is this intended?

const supportsConstructedSheet = (() => {
  try {
    // new CSSStyleSheet()
    // return true
  } catch (e) {}
  return false
})()

Seems that

if (!style) {
     style = document.createElement('style')
     style.setAttribute('type', 'text/css')
     style.innerHTML = content
     document.head.appendChild(style) 

in updateStyle is always triggered for some reason.

@ghost
Copy link
Author

ghost commented Aug 2, 2021

@akrabdev

Is this intended?

Intended to what? Sorry, I didn't get what you mean. I assume the code is commented because it refers to https://wicg.github.io/construct-stylesheets/ which one is still in "A Collection of Interesting Ideas".

in updateStyle is always triggered for some reason.

Sounds truly, but I currently have no idea why.

@ghost
Copy link
Author

ghost commented Aug 2, 2021

Please look at simplified app I've created to see the issue reproduction (look at UPDATE in the issue description).

@ghost

This comment was marked as resolved.

@haoqunjiang

This comment was marked as resolved.

@jerryYuX
Copy link

I also encountered the same problem. When I used antd, the antd style generated two copies, one in the xxx.css file and the other in xxx. js file, which resulted in an increase in the total size of my bundles.

@jerryYuX

This comment was marked as off-topic.

@samarth-math

This comment was marked as off-topic.

@ghost

This comment was marked as spam.

@ghost

This comment was marked as spam.

@phasetri
Copy link

phasetri commented Nov 13, 2021

This is a pretty huge issue. I tried building my project, and noticed that the compiled index.css file is enormous (over 1 MB) despite me only writing a few KB worth of CSS code. If you manually inspect the generated .css files, there are a lot of repeated CSS code.

EDIT: Currently using a workaround where I just import my global SCSS file in the top-most component of my project. In the case of Vue, it's the App.vue file:

<style lang="scss">   // Do not include the "scoped" attribute to allow the rules to propagate to the nested components.
@import "@/css/universal/universal.scss";
</style>

@ghost

This comment was marked as spam.

@samarth-math

This comment was marked as spam.

@jrson83
Copy link

jrson83 commented Feb 14, 2022

I'm having the issue with vite-plugin-ssr. I'm building a page with preact-client-routing example as startpoint.
The issue exists inside this untouched repo. Just clone and try.

If running npm run dev the import './PageShell.css' inside PageShell.jsx is injected as stylesheet and additionally as <style /> tag in the head. You also see the styles always two times inside the styles inspector.

2022-02-14_15h38_14

If running npm run build and npm run server:prod it is injected twice as stylesheet, here _default.page.client.jsx.2942c7fb.css.

2022-02-14_15h39_07

I don't know if this is maybe related to vite-plugin-ssr.

@ghost
Copy link
Author

ghost commented Feb 16, 2022

Will check it in production build. It seems duplication of styles in dev mode is ok since Vite uses HMR. If production build doesn't generate duplicated styles, then is it enough.

@gegorov
Copy link

gegorov commented Mar 1, 2022

same problem even if you use individual imports of common scss file in scss componets files. each import ends up duplicated in final compiled styles.css. using @use instead of @import in .scss files doesn't help.

@sapphi-red

This comment was marked as resolved.

@MrFoxPro

This comment was marked as resolved.

@sapphi-red
Copy link
Member

sapphi-red commented Apr 27, 2022

Sorry my comment was wrong in some parts.

For the following reason, it is not a good choice to import files which include styles with additionalData since it leads to duplicated styles.

  • Vite processes each css import (including sass/scss) indivisually. This is the same behavior with webpack.
  • additionalData is prepended to every scss file which is imported from js.

For example, if you set @use 'foo.scss' to additionalData and the follwing files exists.

// foo.scss
.foo { color: red; }
// bar.scss
.bar { color: green; }
// baz.scss
.baz { color: blue; }
// main.js
import './bar.scss'
import './baz.scss'

bar.scss becomes like below.

.foo { color: red; }
.bar { color: green; }

baz.scss becomes like below.

.foo { color: red; }
.baz { color: blue; }

So the final bundled css becomes like below.

.foo { color: red; }
.bar { color: green; }
.foo { color: red; }
.baz { color: blue; }

If all the scss is bundled at once, it could be deduped. But that is not possible to do during dev and also makes css splitting hard.

@mikeplus64
Copy link
Contributor

For the following reason, it is not a good choice to import files which include styles with additionalData since it leads to duplicated styles.

* Vite processes each css import (including sass/scss) indivisually. This is the same behavior with webpack.

* `additionalData` is prepended to **every** scss file which is imported from js.

I might be misinterpreting what you've said here, but for me with my development builds, I'm not using additionalData at all and am running into the issue of multiple copies of the same stylesheet being generated.

@sapphi-red
Copy link
Member

It will happen by the same reason for an example like below.

/* foo.css */
.foo { color: red; }
/* bar.css */
@import './foo.css'
.bar { color: green; }
/* baz.css */
@import './foo.css'
.baz { color: blue; }
// main.js
import './bar.css'
import './baz.css'

@wesleyboar
Copy link

Will check it in production build. It seems duplication of styles in dev mode is ok since Vite uses HMR. If production build doesn't generate duplicated styles, then is it enough.

When I vite build instead of vite preview, the output CSS still has duplicate content.

@tastytea-github, did you experience the same?

wesleyboar added a commit to TACC/tup-ui that referenced this issue Jun 17, 2022
Such a variable cannot be reduced:
https://github.com/postcss/postcss-calc#usage

Without reduction, i.e. if var stays, var definition must be preserved:
https://github.com/csstools/postcss-plugins/tree/main/plugins/postcss-custom-properties#preserve

If var preserved, then we may be unable to avoid duplicate vars:
vitejs/vite#4448 (comment)
jchuahtacc added a commit to TACC/tup-ui that referenced this issue Jun 22, 2022
* Add UI-Patterns app

* Section exports from core-components

* DescriptionList

* Messages

* Paginator

* Pill

* Dropdown selector

* Same tsconfig settings in tup-ui

* Show more

* Section and Infinite Scroll Table

* Add components for Sidebar (disabled)

* Add react-router-dom v6

* Sidebar

* Formatting and linting

* linting for core-components

* fix(core-components): import failures

1. Load from `src/lib/_imports/`:
    - Can't load core-styles from its `dist`.
    - I don't know why.
    - I do know `.gitignore` is not the problem.\*

    \* I tested disabling it's `dist` entry.

2. Add required CSS file from Portal:
    - Portal used `components/bootstrap.form.css`.
    - CMS did not, but CMS started Core Styles.
    - So Core Styles did not have `…/bootstrap.form.css`.

* fix(core-styles): dist ignore comment, README typo

1. Fix the comment about dist in `.gitignore`.
2. Fix the path inaccuracy in `README`.

* fix(core-components): css syntax & missing values

* feat: postcss config & deps

Tested only with:
- `nx build core-components`
- `nx serve ui-patterns`

* fix(core-components): do not use scss

* docs(core-styles): css lint & syntax highlight

* fix(core-styles): missing css vars from portal

* fix(core-components): explicitely import css vars

* fix(core-components): no css var within calc()

Such a variable cannot be reduced:
https://github.com/postcss/postcss-calc#usage

Without reduction, i.e. if var stays, var definition must be preserved:
https://github.com/csstools/postcss-plugins/tree/main/plugins/postcss-custom-properties#preserve

If var preserved, then we may be unable to avoid duplicate vars:
vitejs/vite#4448 (comment)

* fix(ui-patterns): add missing button patterns

Patterns were recently added to portal: tertiary, active, loading.

They had a couple active state bugs, which I also fixed:
- wrong sample code in UI Pattern for Active button
- class typo in Button.module.css

* fix(core-styles): explicit var import for patterns

This should be done to all core-styles stylesheets.

But that will have an uncertain effect on CMS.

So for now, just make this work for core-components.

* fix:(ui-patterns): show actual class name passed

Mimicked by: TACC/Core-Portal#663

* fix(core-styles): add missing font family vars

* fix(ui-patterns): explicit var import for patterns

Just like I did earlier for core-components: 4c0bf2b.

* chore(ui-patterns): do not import unused styles

* chore(tup-ui): do not import unused styles

* docs(ui-patterns): link to ITCSS organization doc

* docs(tup-ui): link to ITCSS organization doc

* feat(core-styles): add o-fixed-header-table

* feat(core-components): use o-fixed-header-table

Use o-fixed-header-table for InfiniteScrollTable via core-styles.

* feat(core-styles): cortal icons

* fix(core-components): icon styles, font, props

* fix(ui-patterns): missing space between buttons

* feat(core-styles): components/bootstrap.modal.css

* feat: install bootstrap ^4.6.0

* fix(ui-patterns): global css (inc. bootstrap)

also, re-document (simpler, broader) index.css

* fix(core-components): hide Spinner Loading... text

* fix(core-components): do not use Reactstrap Button

* fix(core-components): (wip) tsx button prop limits

Restrict combinations of button props type and size.

Works only in file. Does not work in practice:
- Use <Button> with bad props in Button.tsx, VS Code complains.
- Use <Button> with bad props in UIPatternsButton.tsx, VS Code ignores.

Also, removed related test cases, cuz TypeScript prevents need, right?

* fix(core-styles): auto width for size-less buttons

Set a default width for buttons that:
- have no width
- have no size
- are not links

This resolves ac5dcf8 having removed default size.

* fix(core-components): mostly no use native button

- Do not use native button for typical buttons.
- The close button for Messages is atypical.

* fix(core-components): ShowMore Button type

This was not completely converted from Reactstrap to Core Component.

* fix(ui-patterns): nx format:write

* fix(core-components): nx format:write

* fix(core-styles): nx format:write

* fix: match reactstrap version to bootstrap version

* Revert "fix(core-components): hide Spinner Loading... text"

This reverts commit d5bfc79.

Since commit 4a873cb," Loading..." text is automatically hidden.
- Reactstrap 9 and Bootstrap 5 use ".visually-hidden" class.
- Rectstrap 8 and Bootstrap 4 uses ".sr-only" class.

To avoid other unexpected bugs, I suggest same Bootstrap as CEPv2.

Or… we reveal and fix any bugs (reference Bootstrap 4 → 5 migration).

* fix(core-styles): vertically align button content

Why `c-button` not `cortal.icon`?
- This must be applied to the text and icon elements to work.

Why not use inline-flex et cetera?
- Because sibling buttons vertical alignment broken when I tried it.

Inspiration: TACC/Core-Portal@307c54a

* fix(tup-ui): style links, no use wb-link

Style hyperlinks. Remove unused "wb-link" classes.

* fix(core-components): message no override .wb-link

1. Message need not overwrite ".wb-link" (class dropped in 08ad3da).
2. Add an active state. \*

\* Design does not care to distinguish link states.

* fix(ui-patterns): activeClassN… react-r…-dom ver.

Use same react-router-dom version as CEPv2 to make activeClassName work.
- downgrade react-router-dom
- use switch and component props

* fix(core-components): Sidebar styles

1. Remove unused class "nav-content".
2. Use anchor tag pseduo classes to overwrite "elements.css".
3. Add missing style for nav content.

Depends on: e859114 (i.e. previous commit)

* feat(core-components): simpler Sidebar styles

1. No "content" wrapper div.
2. Move "content" wrapper div styles to link.
3. Move text padding to icon.
  - Because the padding exists only because icon exists.
  - Required adding a Sidebar "icon" class.

Builds off: 2243276 (i.e. previous commit)

* chore(ui-patterns): nx format:write

* chore(core-comp…s): load form css at dist not src

* chore(core-comp…s): load css settings from dist

Co-authored-by: Joon-Yee Chuah <jchuah@tacc.utexas.edu>
@Bunkerbewohner
Copy link

I also have experienced this issue. In my case the same '.less' file is imported by several other modules, and this leads to several duplicate <style> elements in the header that all contain the same CSS. It still works, but surely it would be better if only one style element would be injected for each CSS file.

jchuahtacc added a commit to TACC/tup-ui that referenced this issue Jul 25, 2022
* task/TUP-272 - core components fixup (#7)

* feat(core-components): copy & polish from cepv2

These comp…s:
- were copied from cepv2
- were made more modular
- have react-based dependencies

Not cepv2 comp…s were copied, because some are not easy to make modular.

Comp…s were copied May 4, 2022. Some have since changed in CEPv2, e.g.:
- Button
- Paginator
- (maybe) Message

* feat(comp…s): cepv2 update but w/ new styles paths

Source: TACC/Core-Portal#639

* feat(comp…s): 2nd cepv2 update (no path updates)

* feat(comp…s): cepv2 update: button tests, unmerged

Source: TACC/Core-Portal#640

* fix(comp…s): fix core-styles paths (libs → lib)

* feat(comp…s): update all paths to core-styles src

Some of these may be able to use dist... I haven't checked yet.

* feat(comp…s): fix paths that can use styles dist

One of the paths is still src/lib/_imports. CMS has this problem often.

To use src/lib/_imports instead of dist, see TUP-274.

* fix(styles): all src/lib imports to use rel. paths

Avoid users needing resolution paths specific to core-styles hierarchy.

* fix(styles): src/lib rel. paths need no _imports/

Hotfix previous commit: aab21ba
"fix(styles): all src/lib imports to use rel. paths"

* fix(tup-ui): load CSS from correct path

* Convert Button and dependencies to TS

* Add reactstrap global

* Replace temporary Message component to exports

* Use Button from core-components in tup-ui

* Added babel-plugin-postcss for core-components

* Formatting

* linting

* Formatting

* Task/tup 272  core components vite (#8)

* Vite library build for core-components

* Icon allows react node children

* Add testing-library/react

* Fix tests

* Fix test

* Formatting

* vite output directory

* clean tup-ui on build

Co-authored-by: Wesley Bomar <wbomar@tacc.utexas.edu>

* task/TUP-280 -- UI patterns (#12)

* Add UI-Patterns app

* Section exports from core-components

* DescriptionList

* Messages

* Paginator

* Pill

* Dropdown selector

* Same tsconfig settings in tup-ui

* Show more

* Section and Infinite Scroll Table

* Add components for Sidebar (disabled)

* Add react-router-dom v6

* Sidebar

* Formatting and linting

* linting for core-components

* task/TUP-280, 282, 283 -- UI patterns (fixes), CSS vars, styles (#14)

* Add UI-Patterns app

* Section exports from core-components

* DescriptionList

* Messages

* Paginator

* Pill

* Dropdown selector

* Same tsconfig settings in tup-ui

* Show more

* Section and Infinite Scroll Table

* Add components for Sidebar (disabled)

* Add react-router-dom v6

* Sidebar

* Formatting and linting

* linting for core-components

* fix(core-components): import failures

1. Load from `src/lib/_imports/`:
    - Can't load core-styles from its `dist`.
    - I don't know why.
    - I do know `.gitignore` is not the problem.\*

    \* I tested disabling it's `dist` entry.

2. Add required CSS file from Portal:
    - Portal used `components/bootstrap.form.css`.
    - CMS did not, but CMS started Core Styles.
    - So Core Styles did not have `…/bootstrap.form.css`.

* fix(core-styles): dist ignore comment, README typo

1. Fix the comment about dist in `.gitignore`.
2. Fix the path inaccuracy in `README`.

* fix(core-components): css syntax & missing values

* feat: postcss config & deps

Tested only with:
- `nx build core-components`
- `nx serve ui-patterns`

* fix(core-components): do not use scss

* docs(core-styles): css lint & syntax highlight

* fix(core-styles): missing css vars from portal

* fix(core-components): explicitely import css vars

* fix(core-components): no css var within calc()

Such a variable cannot be reduced:
https://github.com/postcss/postcss-calc#usage

Without reduction, i.e. if var stays, var definition must be preserved:
https://github.com/csstools/postcss-plugins/tree/main/plugins/postcss-custom-properties#preserve

If var preserved, then we may be unable to avoid duplicate vars:
vitejs/vite#4448 (comment)

* fix(ui-patterns): add missing button patterns

Patterns were recently added to portal: tertiary, active, loading.

They had a couple active state bugs, which I also fixed:
- wrong sample code in UI Pattern for Active button
- class typo in Button.module.css

* fix(core-styles): explicit var import for patterns

This should be done to all core-styles stylesheets.

But that will have an uncertain effect on CMS.

So for now, just make this work for core-components.

* fix:(ui-patterns): show actual class name passed

Mimicked by: TACC/Core-Portal#663

* fix(core-styles): add missing font family vars

* fix(ui-patterns): explicit var import for patterns

Just like I did earlier for core-components: 4c0bf2b.

* chore(ui-patterns): do not import unused styles

* chore(tup-ui): do not import unused styles

* docs(ui-patterns): link to ITCSS organization doc

* docs(tup-ui): link to ITCSS organization doc

* feat(core-styles): add o-fixed-header-table

* feat(core-components): use o-fixed-header-table

Use o-fixed-header-table for InfiniteScrollTable via core-styles.

* feat(core-styles): cortal icons

* fix(core-components): icon styles, font, props

* fix(ui-patterns): missing space between buttons

* feat(core-styles): components/bootstrap.modal.css

* feat: install bootstrap ^4.6.0

* fix(ui-patterns): global css (inc. bootstrap)

also, re-document (simpler, broader) index.css

* fix(core-components): hide Spinner Loading... text

* fix(core-components): do not use Reactstrap Button

* fix(core-components): (wip) tsx button prop limits

Restrict combinations of button props type and size.

Works only in file. Does not work in practice:
- Use <Button> with bad props in Button.tsx, VS Code complains.
- Use <Button> with bad props in UIPatternsButton.tsx, VS Code ignores.

Also, removed related test cases, cuz TypeScript prevents need, right?

* fix(core-styles): auto width for size-less buttons

Set a default width for buttons that:
- have no width
- have no size
- are not links

This resolves ac5dcf8 having removed default size.

* fix(core-components): mostly no use native button

- Do not use native button for typical buttons.
- The close button for Messages is atypical.

* fix(core-components): ShowMore Button type

This was not completely converted from Reactstrap to Core Component.

* fix(ui-patterns): nx format:write

* fix(core-components): nx format:write

* fix(core-styles): nx format:write

* fix: match reactstrap version to bootstrap version

* Revert "fix(core-components): hide Spinner Loading... text"

This reverts commit d5bfc79.

Since commit 4a873cb," Loading..." text is automatically hidden.
- Reactstrap 9 and Bootstrap 5 use ".visually-hidden" class.
- Rectstrap 8 and Bootstrap 4 uses ".sr-only" class.

To avoid other unexpected bugs, I suggest same Bootstrap as CEPv2.

Or… we reveal and fix any bugs (reference Bootstrap 4 → 5 migration).

* fix(core-styles): vertically align button content

Why `c-button` not `cortal.icon`?
- This must be applied to the text and icon elements to work.

Why not use inline-flex et cetera?
- Because sibling buttons vertical alignment broken when I tried it.

Inspiration: TACC/Core-Portal@307c54a

* fix(tup-ui): style links, no use wb-link

Style hyperlinks. Remove unused "wb-link" classes.

* fix(core-components): message no override .wb-link

1. Message need not overwrite ".wb-link" (class dropped in 08ad3da).
2. Add an active state. \*

\* Design does not care to distinguish link states.

* fix(ui-patterns): activeClassN… react-r…-dom ver.

Use same react-router-dom version as CEPv2 to make activeClassName work.
- downgrade react-router-dom
- use switch and component props

* fix(core-components): Sidebar styles

1. Remove unused class "nav-content".
2. Use anchor tag pseduo classes to overwrite "elements.css".
3. Add missing style for nav content.

Depends on: e859114 (i.e. previous commit)

* feat(core-components): simpler Sidebar styles

1. No "content" wrapper div.
2. Move "content" wrapper div styles to link.
3. Move text padding to icon.
  - Because the padding exists only because icon exists.
  - Required adding a Sidebar "icon" class.

Builds off: 2243276 (i.e. previous commit)

* chore(ui-patterns): nx format:write

* chore(core-comp…s): load form css at dist not src

* chore(core-comp…s): load css settings from dist

Co-authored-by: Joon-Yee Chuah <jchuah@tacc.utexas.edu>

* fix(core-components): missing dependency, dependency alternative (#13)

* fix(core-components): CSS and Dependency imports

* chore(tup-ui): minimize #13 diff

* chore(core-components): minimize diff ie remove space

* task/TUP - 284 -- core wrappers (#15)

* Port tapis-ui/_wrappers

* UIPatternsComplexWizard

* Fix components to switch rather than route

* Field array of field arrays step

* Simple wizard

* Formatting and linting

* Fix wizard continue

* Fix complex wizards value loading

* Clarity on initialvalues vs defaultvalues in simple wizard

* Formatting

* Fix unit tests

* fix collapse icon

* Replace ErrorMessage component with formtext

* Fix config files

* Formatting

* Add validation to wizards

* Bump react-router-dom to v6.3.0

* Version bump reactstrap

* navlink active classname

Co-authored-by: Wesley Bomar <wbomar@tacc.utexas.edu>
Co-authored-by: Wesley B <62723358+wesleyboar@users.noreply.github.com>
@jpengelbrecht
Copy link

running into this issue on the newer versions as well

@dsvgl
Copy link

dsvgl commented Oct 13, 2022

please have a look at my answer to this (same) issue: https://github.com/nuxt/framework/discussions/8139#discussioncomment-3864265

TL;DR
Don't include scss files with actual css-rules via additionalData. Only files that include variables, mixins, etc.
Working example: https://stackblitz.com/edit/github-hq9bhi?file=app.vue

@cwe-spb
Copy link

cwe-spb commented Oct 17, 2022

@dsvgl how i can add global css rules then?

@Alihd1
Copy link

Alihd1 commented Dec 22, 2022

Any update on this issue? is there a solution?

@dschmidt
Copy link

Here's what I've come up with:

const stripScssMarker = '/* STYLES STRIP IMPORTS MARKER */'

export default {
css: {
        preprocessorOptions: {
          scss: {
            additionalData: `@import "${projectRootDir}/shared_styles";${stripScssMarker}`
          }
        }
      },
plugins: [
{
          name: 'vite-plugin-strip-css',
          transform(src: string, id) {
            if (id.endsWith('.vue') && !id.includes('node_modules') && src.includes('@extend')) {
              console.warn(
                'You are using @extend in your component. This is likely not working in your styles. Please use mixins instead.',
                id.replace(`${projectRootDir}/`, '')
              )
            }
            if (id.includes('lang.scss')) {
              const split = src.split(stripScssMarker)
              const newSrc = split[split.length - 1]

              return {
                code: newSrc,
                map: null
              }
            }
          }
        }]
}

Just needs an additional import of the style file from index.html. I had to create a shared_styles_proxy.scss file which imports the shared_styles.scss because otherwise vite would tell me shared_style.scss was already imported.

The downside is that code that modifies the shared style doesn't work like this. We had to get rid of all @extend usages in our codebase, which luckily were only a few.

Hope this helps.

@jaydiazzz

This comment was marked as spam.

@cwe-spb

This comment was marked as spam.

@RohitKaushal7
Copy link

Is this issue not fixable..?

@dschmidt
Copy link

dschmidt commented Apr 3, 2023

Is this issue not fixable..?

It would be incredibly hard to fix it in a generic way, see my answer for a workaround that is applicable in certain circumstances (if you don't use @extend).

@RohitKaushal7
Copy link

RohitKaushal7 commented Apr 3, 2023

@dschmidt Yes I used your workaround. It works perfectly fine. 💘 Thank You.

I was facing an issue that was also removing other imports ( google fonts etc.. ) which I fixed by excluding my main file (which also had the fonts imports) from this replacement.
PS: I am using vite with react.

const SPLIT_CSS_MARK = '/* ##SPLIT_CSS_MARK## */'
export default ({ command }) => {
  return defineConfig({
    ...
    plugins: [
      ...
      {
        // ⚙️ custom plugin to remove duplicated css caused by css.preprocessorOptions.scss.additionalData
        name: 'vite-plugin-strip-css',
        transform(src: string, id) {
          if (id.includes('.scss')) {
            if (id.includes('src/index.scss')) {
              // Keep the common file only in root css file
              return { code: src, map: null }
            }

            const split = src.split(SPLIT_CSS_MARK)
            const newSrc = split[split.length - 1]
            return { code: newSrc, map: null }
          }
        },
      },
    ],
    css: {
      preprocessorOptions: {
        scss: {
          additionalData:
            `@use "./src/styles/common.scss" as *;` + SPLIT_CSS_MARK,
        },
      },
    },
  })
}

@github-actions github-actions bot locked and limited conversation to collaborators Apr 19, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.