feat: add cssInject option for library mode#21640
Open
veeceey wants to merge 2 commits intovitejs:mainfrom
Open
feat: add cssInject option for library mode#21640veeceey wants to merge 2 commits intovitejs:mainfrom
veeceey wants to merge 2 commits intovitejs:mainfrom
Conversation
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`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1579
What this does
When building a library with
build.lib, CSS gets extracted to a separate.cssfile 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.cssInjectoption that injects the CSS directly into the JavaScript output at runtime using a lightweightstyleInjecthelper. When the library is loaded, it creates a<style>element and appends it to<head>.Usage
This produces a single JS file with no separate CSS file. The CSS is injected at runtime when the module is loaded.
Changes
cssInjectoption toLibraryOptionsinterfacecssPostPlugin'sgenerateBundleto inject CSS into entry chunks instead of emitting a separate CSS file whencssInject: truecjsformat support toinjectInlinedCSS(was missing, only supportedes,iife,umd)vite.css-inject.config.js)Notes
cssInjectoption wraps the injection in a try/catch so it won't break in non-DOM environments (though it won't inject styles there either)es,cjs,umd,iifefalseto maintain backwards compatibility