vite: Dependency Pre-Bundling does not bundle styles

Describe the bug

Dependency pre-bundling does not bundle CSS (or other css langs; in this case, SASS) imports within dependencies.

The result of this is that in serve mode when using component frameworks like Vuetify with per-component imports, each individual CSS file for each individual component is loaded with an independent HTTP request, even though all the scripts for these components are bundled into a single file.

This results in 100+ extra HTTP requests in serve mode.

Reproduction

https://github.com/ascott18/repro-vite-css-prebundling

System Info

System:
    OS: Windows 10 10.0.19044
    CPU: (16) x64 Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz   
    Memory: 12.01 GB / 31.94 GB
  Binaries:
    Node: 16.13.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.15.2 - C:\Program Files (x86)\Yarn\bin\yarn.CMD  
    npm: 8.1.3 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Chrome: 100.0.4896.75
    Edge: Spartan (44.19041.1266.0), Chromium (100.0.1185.36)
    Internet Explorer: 11.0.19041.1566
  npmPackages:
    vite: 2.9.3 => 2.9.3

Used Package Manager

npm

Logs

(including image because I can’t capture Chrome network tools output in a reasonable text format) image

Validations

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 11
  • Comments: 27 (3 by maintainers)

Most upvoted comments

After some tinkering, I was able to achieve the desired outcome here using the following configuration. Took a while to figure out since extensions is undocumented. (Other experimental features are documented, like SSR - is this an oversight?):

    optimizeDeps: {
      extensions: [".scss", ".sass"],
      esbuildOptions: {
        plugins: [
          (await import("esbuild-sass-plugin")).sassPlugin({
            type: "style",
            // Setting `logger.warn` to no-op is a workaround for
            // https://github.com/sass/sass/issues/3065#issuecomment-868302160.
            // Since `optimizeDeps` is only processing third party dependencies and only during dev,
            // we don't care about *any* deprecation warnings. The `quietDeps` SASS option doesn't work.
            logger: { warn() {} },
          }),
        ],
      },
    },

Would there ever be consideration to making this functionality baseline? Since build mode supports popular CSS preprocessors, I think it would make sense to also support them here in serve. I realize that different “glue” would have to be built to plug them into esbuild rather than rollup (as to not add third-party dependencies like I did in my config here). Is this something that would be worth my while to start a PR for?

This option is necessary for component-specific SASS variable overrides. Webpack does not have this issue. I tried adding all components and SASS from Vuetify to the Vite server warmup configuration (https://vitejs.dev/config/server-options.html#server-warmup), but that doesn’t seem to work either.

I’m wondering if this is a Vite issue or a Vuetify issue. I’ve spoken to @johnleider from Vuetify, and they are unsure what to do differently with the Vuetify loader. It would be great if someone from Vite could let us know if Vuetify needs to make any changes or if this is a Vite issue that we need to wait for a fix on.

And perhaps the label “has workaround” should be removed, or could anyone tell me what the workaround is, i’ve tried everything.

With vuetify this specific time issue happens when you use vuetifys sass variables file AND use component specific sass variables.

So once you add this to the vite config:

export default defineConfig({
  plugins: [
    // https://github.com/vuetifyjs/vuetify-loader/tree/master/packages/vite-plugin#readme
    vuetify({ styles: { configFile: "src/styles/settings.scss" } }),
  ],

and change @use 'vuetify' with ( into @use 'vuetify/settings' with ( in your settings.scss

I guess because every sass file vuetify imports needs to be recompiled to add the settings.scss above it.

I’ve had contact with the founder from vuetify, but they don’t know how to resolve it and if they are doing something the wrong way, they like to know it.

Hopefully anyone knows how to handle this, in any way. Can i do something? Does vuetify have to do something? Does vite need to change anything?

Thanks for providing a reproduction. I had a look and it appears that there are a few intertwined issues, so try to comment on them separately.

First of all, pre-bundling scss/sass files using esbuild-sass-plugin should technically work at least for simple cases. I made a small example here https://github.com/hi-ogawa/reproductions/tree/main/vite-sass-pre-bundling and required configuration looks like this (which were briefly mentioned in https://github.com/vitejs/vite/issues/7719#issuecomment-1694483567)

import { defineConfig } from 'vite'
import { sassPlugin } from "esbuild-sass-plugin";

export default defineConfig({
  optimizeDeps: {
    extensions: [".scss", ".sass"],
    esbuildOptions: {
      plugins: [
        sassPlugin({
          // default `type: "css"` doesn't work since it emits separate css files
          // and removes css import from js files.
          // https://esbuild.github.io/content-types/#css-from-js
          // https://github.com/glromeo/esbuild-sass-plugin#type-style
          type: "style",
        }),
      ]
    }
  }
})

The reason why this approach is not working specifically for vuetify is that because it relies on vite plugin to rewrite original .css import into .sass virtual module https://github.com/vuetifyjs/vuetify-loader/blob/e1587d8d6b9da45d159ec5eee39cfa901bc61aca/packages/vite-plugin/src/stylesPlugin.ts#L54-L58. This mechanism is probably difficult to apply to pre-bundling which is based on esbuild.


2nd issue is that current Vite’s default sass setup is not best for speed performance. As I mentioned in https://github.com/vitejs/vite/issues/7719#issuecomment-2255383411, it’s planned to integrate improved sass compilation API inside Vite. Before this feature is available, there are already two ways you might be able to improve performance by using css.preprocessorMaxWorkers https://vitejs.dev/config/shared-options.html#css-preprocessormaxworkers or sass-embedded package via alias (cf. https://github.com/vitejs/vite/issues/6734#issuecomment-1492975259). This is the result when I tested https://github.com/ricardovanlaarhoven/vuetify-vite-sass-speed-issues on my machine:

default

image

preprocessorMaxWorkers: true

Image

sass-embedded

Image


3rd issue is that you are likely experiencing frequent full-reload on navigation due to deps optimization triggered when discovering new dependencies in new pages. This is a different issue on its own and it happens when Vite’s default heuristics is not able to discover dependencies used in user source code. For example, you can find a similar issue and potential solutions discussed on https://github.com/nuxt/nuxt/issues/26783 (I also remember other Vite frameworks like Sveltekit, Remix etc… experienced a similar issue). I tried optimizeDeps.exclude: ["vuetify"] in https://github.com/ricardovanlaarhoven/vuetify-vite-sass-speed-issues and indeed it looks like it can prevent spontaneous full-reload when navigating from / to /test (even though this will prevent pre-bundling and increase the number of js requests).


From what I can see, this issue having “has workaround” status seems right. I think it’s still possible to improve vuetify (+ custom sass configFile) experience by figuring out 2nd and 3rd issues.

I’ve created a new vuetify project, added some sass variables and this is the result:

image

https://github.com/ricardovanlaarhoven/vuetify-vite-sass-speed-issues

Vuetify with vite speed issue

run pnpm install run pnpm dev go to localhost:300 go to the network tab and see a lot of pending sass/scss requests Once done, click on the Go to test link And once again see a lot of pending requests When you repeat this, the speed is excelent When you cut the server, and rerun pnpm dev, the speed is slow again for the first time.

Keep in mind that this is a really really small project, just the starter of vuetify with 3 simple components on the test page. My pc the loading time is about 4s here. On my real project, it’s about 20s and after every new page with 1 simple new component again. This test project only has 1 page.

You could add some more pages and components to see the difference in speed. For exmaple adding VDataTable adds makes it go up to 11 seconds

@ascott18 thanks for the workaround.

One more precision

vuetify 2 is limited to sass v1.32, see discussion https://github.com/vuetifyjs/vuetify/issues/13694#issuecomment-852957010

To satisfy this dependencie, need to have { "esbuild-sass-plugin": "^1.7.0" } in package.json

Thnx @hi-ogawa For taking so much time to investigate this with me. Perhaps @KaelWD from vuetify can read along with us.

I’ve tested it in my real-life project. I’m on a table page with already a lot of vuetify components, and going to a form page, it takes 48 seconds to load. When adding the following

   optimizeDeps: { exclude: ["vuetify"] },
   css: { preprocessorMaxWorkers: true },

it takes 9 seconds

When doing pnpm i -D sass@npm:sass-embedded@1.77.5 Mind that i have to change the version since vuetifyhas some deprecations (https://sass-lang.com/d/mixed-dec)

it takes 9 seconds

But i do still use the optimizeDeps and preprocessorMaxWorkers. And perhaps i’m not doing enough?

I’m grateful for the impressive time-cut.

a few points/questions:

  • @KaelWD could vuetify do something with the first point?
  • @hi-ogawa adding the optimizeDeps has one downside, the first time you open the app, it goed to a white screen after loading. Then i can refresh the browser page and sometimes it’s immidiatly there, sometimes i have to refresh one last time.
  • @hi-ogawa did i do anything wrong with the sass embed workaround?
  • @hi-ogawa When to excpect the improbed sass api? vite 5.4? or 6 or?

This actually helped me a lot, almost instantly starting my large project in dev mode

adding the optimizeDeps has one downside, the first time you open the app, it goed to a white screen after loading. Then i can refresh the browser page and sometimes it’s immidiatly there, sometimes i have to refresh one last time.

Figuring this out requires more domain knowledge of framework/library side and app specifics. I’m not familiar with Vue in general, so probably it’s better to seek a help elsewhere.

did i do anything wrong with the sass embed workaround?

When using sass-embedded override, having preprocessorMaxWorkers: true might have a negative effect. Can you try removing it? (cf. https://github.com/hi-ogawa/test-vite-sass/issues/1#issuecomment-2249076746)

When to excpect the improbed sass api? vite 5.4? or 6 or?

Hopefully the improvement will be available in v5.4. One PR is merged https://github.com/vitejs/vite/pull/17728 and next one https://github.com/vitejs/vite/pull/17754 is also hopefully merged for 5.4.

Thnx @hi-ogawa For taking so much time to investigate this with me. Perhaps @KaelWD from vuetify can read along with us.

I’ve tested it in my real-life project. I’m on a table page with already a lot of vuetify components, and going to a form page, it takes 48 seconds to load. When adding the following

   optimizeDeps: { exclude: ["vuetify"] },
   css: { preprocessorMaxWorkers: true },

it takes 9 seconds

When doing pnpm i -D sass@npm:sass-embedded@1.77.5 Mind that i have to change the version since vuetifyhas some deprecations (https://sass-lang.com/d/mixed-dec)

it takes 9 seconds

But i do still use the optimizeDeps and preprocessorMaxWorkers. And perhaps i’m not doing enough?

I’m grateful for the impressive time-cut.

a few points/questions:

  • @KaelWD could vuetify do something with the first point?
  • @hi-ogawa adding the optimizeDeps has one downside, the first time you open the app, it goed to a white screen after loading. Then i can refresh the browser page and sometimes it’s immidiatly there, sometimes i have to refresh one last time.
  • @hi-ogawa did i do anything wrong with the sass embed workaround?
  • @hi-ogawa When to excpect the improbed sass api? vite 5.4? or 6 or?

@ascott18 It’s work but it’s breaks the next settings:

css: {
  preprocessorOptions: {
    sass: {
      additionalData: [
        '@import "./src/styles/variables.sass"',
        '',
      ].join('\n'),
    }
  }
},

@ricardovanlaarhoven It’s the same for me and on huge projects is very time consuming.

@ricardovanlaarhoven I assume an object is passed to your defineConfig instead of an async function.

export default defineConifg(async () => ({ // now you can do await import }))