Skip to content

Comments

feat: add cssInject option for library mode#21640

Open
veeceey wants to merge 2 commits intovitejs:mainfrom
veeceey:feat/issue-1579-css-inject-library
Open

feat: add cssInject option for library mode#21640
veeceey wants to merge 2 commits intovitejs:mainfrom
veeceey:feat/issue-1579-css-inject-library

Conversation

@veeceey
Copy link

@veeceey veeceey commented Feb 15, 2026

Closes #1579

What this does

When building a library with build.lib, CSS gets extracted to a separate .css file by default. This means consumers have to manually import both the JS and the CSS, which is a pain point for component libraries.

This PR adds a build.lib.cssInject option that injects the CSS directly into the JavaScript output at runtime using a lightweight styleInject helper. When the library is loaded, it creates a <style> element and appends it to <head>.

Usage

export default defineConfig({
  build: {
    lib: {
      entry: 'src/index.ts',
      name: 'MyLib',
      cssInject: true,
    },
  },
})

This produces a single JS file with no separate CSS file. The CSS is injected at runtime when the module is loaded.

Changes

  • Added cssInject option to LibraryOptions interface
  • Modified cssPostPlugin's generateBundle to inject CSS into entry chunks instead of emitting a separate CSS file when cssInject: true
  • Added cjs format support to injectInlinedCSS (was missing, only supported es, iife, umd)
  • Added unit test for CJS format injection
  • Added playground test with a dedicated config (vite.css-inject.config.js)

Notes

  • The cssInject option wraps the injection in a try/catch so it won't break in non-DOM environments (though it won't inject styles there either)
  • Works with all library formats: es, cjs, umd, iife
  • Default is false to maintain backwards compatibility

veeceey and others added 2 commits February 14, 2026 22:54
Add `build.lib.cssInject` option that injects CSS into the JavaScript
output via a runtime styleInject helper instead of emitting a separate
CSS file. This allows library consumers to import a single JS file
without needing to separately import CSS.

Also adds `cjs` format support to `injectInlinedCSS`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Can css be styleInjected in library mode?

1 participant