Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A Vite plugin that takes the CSS and adds it to the page through the JS. For those who want a single JS file.

License

NotificationsYou must be signed in to change notification settings

marco-prontera/vite-plugin-css-injected-by-js

A Vite plugin that takes the CSS and adds it to the page through the JS. For those who want a single JS file.

The plugin can be configured to execute the CSS injection before or after your app code, and you can also provide acustom id for the injected style element and other configurations that fulfill some particular cases, even for libs.

How does it work

Essentially what it does is take all the CSS generated by the build process and add it via JavaScript. The CSS file istherefore not generated and the declaration in the generated HTML file is also removed. You can also configure when theCSS injection will be executed (before or after your app code).

Installation

npm i vite-plugin-css-injected-by-js --save

Usage

importcssInjectedByJsPluginfrom'vite-plugin-css-injected-by-js'exportdefault{plugins:[cssInjectedByJsPlugin(),]}

Configurations

When you add the plugin, you can provide a configuration object. Below you can find all configuration parametersavailable.

cssAssetsFilterFunction (function)

ThecssAssetsFilterFunction parameter allows you to specify a filter function that will enable you to exclude someoutput css assets.

This option is not applied torelativeCSSInjection logic.

Here is an example of how to use thecssAssetsFilterFunction:

importcssInjectedByJsPluginfrom'vite-plugin-css-injected-by-js'exportdefault{plugins:[cssInjectedByJsPlugin({cssAssetsFilterFunction:functioncustomCssAssetsFilterFunction(outputAsset){returnoutputAsset.fileName=='font.css';}}),]}

dev (object)

EXPERIMENTALWhy experimental? Because it uses a non-conventional solution.

Previously, the plugin strictly applied logic solely during the build phase. Now, we have the capability to experimentwith it in the development environment.

To activate the plugin in the development environment as well, you need to configure a dev object and set the enableDevparameter to true.

Here's an example:

importcssInjectedByJsPluginfrom'vite-plugin-css-injected-by-js'exportdefault{plugins:[cssInjectedByJsPlugin({dev:{enableDev:true,removeStyleCodeFunction:functionremoveStyleCode(id:string){// The 'id' corresponds to the value of the 'data-vite-dev-id' attribute found on the style element. This attribute is visible even when the development mode of this plugin is not activated.}}}),]}

This approach should serve its purpose effectively unless you're employing custom injection code to insert styles wherenecessary. Since the development environment involves the concept of "updating" styles in the Document Object Model (DOM), this plugin requires code to remove the injected style from the DOM.

Due to these factors, if you're utilizing custom injection code (viainjectCode orinjectCodeFunction), the plugincannot automatically discern how to delete the injected style. Therefore, all you need to do is configureeitherremoveStyleCode orremoveStyleCodeFunction within thedev object as demonstrated above.

NOTE: TheinjectCode andinjectCodeFunction parameters now also include theattributes, and indev mode,theattributes object encompasses thedata-vite-dev-id as well. Refer to theinjectCodeFunction example below forfurther details.

injectCode (function)

You can provide also a function forinjectCode param to customize the injection code used. TheinjectCode callbackmust return astring (with valid JS code) and it's called with two arguments:

  • cssCode (thestring that contains all the css code that need to be injected via JavaScript)
  • options (an object withstyleId,useStrictCSP andattributes the last is an object that represent the attributesof the style element that should have)

This is an example:

importcssInjectedByJsPluginfrom'vite-plugin-css-injected-by-js'exportdefault{plugins:[cssInjectedByJsPlugin({injectCode:(cssCode:string,options:InjectCodeOptions)=>{return`try{if(typeof document != 'undefined'){var elementStyle = document.createElement('style');elementStyle.appendChild(document.createTextNode(${cssCode}));document.head.appendChild(elementStyle);}}catch(e){console.error('vite-plugin-css-injected-by-js', e);}`}}),]}

injectCodeFunction (function)

If you prefer to specify the injectCode as a plain function you can use theinjectCodeFunction param.

TheinjectCodeFunction function is a void function that will be called at runtime application with two arguments:

  • cssCode (thestring that contains all the css code that need to be injected via JavaScript)
  • options (an object withstyleId,useStrictCSP andattributes the last is an object that represent the attributesof the style element that should have)

This is an example:

importcssInjectedByJsPluginfrom'vite-plugin-css-injected-by-js'exportdefault{plugins:[cssInjectedByJsPlugin({injectCodeFunction:functioninjectCodeCustomRunTimeFunction(cssCode:string,options:InjectCodeOptions){try{if(typeofdocument!='undefined'){varelementStyle=document.createElement('style');// SET ALL ATTRIBUTESfor(constattributeinoptions.attributes){elementStyle.setAttribute(attribute,options.attributes[attribute]);}elementStyle.appendChild(document.createTextNode(${cssCode}));document.head.appendChild(elementStyle);}}catch(e){console.error('vite-plugin-css-injected-by-js',e);}}}),]}

injectionCodeFormat (ModuleFormat)

You can specify the format of the injection code, by default isiife.

jsAssetsFilterFunction (function)

ThejsAssetsFilterFunction parameter allows you to specify which JavaScript file(s) the CSS injection code should beadded to. This is useful when using a Vite configuration that exports multiple entry points in the building process. Thefunction takes in an OutputChunk object and should return true for the file(s) you wish to use as the host of the CSSinjection. If multiple files are specified, the CSS injection code will be added to all files returned as true.

Here is an example of how to use thejsAssetsFilterFunction:

importcssInjectedByJsPluginfrom'vite-plugin-css-injected-by-js'exportdefault{plugins:[cssInjectedByJsPlugin({jsAssetsFilterFunction:functioncustomJsAssetsfilterFunction(outputChunk){returnoutputChunk.fileName=='index.js';}}),]}

In this example, the CSS injection code will only be added to theindex.js file. If you wish to add the code tomultiple files, you can specify them in the function:

importcssInjectedByJsPluginfrom'vite-plugin-css-injected-by-js'exportdefault{plugins:[cssInjectedByJsPlugin({jsAssetsFilterFunction:functioncustomJsAssetsfilterFunction(outputChunk){returnoutputChunk.fileName=='index.js'||outputChunk.fileName=='subdir/main.js';}}),]}

This code will add the injection code to both index.js and main.js files.Be aware that if you specified multiple files that the CSS can be doubled.

preRenderCSSCode (function)

You can use thepreRenderCSSCode parameter to make specific changes to your CSS before it is printed in the output JSfile. This parameter takes the CSS code extracted from the build process and allows you to return the modified CSS codeto be used within the injection code.

This way, you can customize the CSS code without having to write additional code that runs during the execution of yourapplication.

This is an example:

importcssInjectedByJsPluginfrom'vite-plugin-css-injected-by-js'exportdefault{plugins:[cssInjectedByJsPlugin({preRenderCSSCode:(cssCode)=>cssCode}),// The return will be used as the CSS that will be injected during execution.]}

relativeCSSInjection (boolean)

This feature is based on information provided by Vite. Since we can't control how Vite handles this information thismeans that there may be problems that may not be possible to fix them in this plugin.

The default behavior of this plugin takes all the CSS code of your application directly to the entrypoint generated.TherelativeCSSInjection if configured totrue will inject the CSS code of every entrypoint to the relativeimporter.

Set this option totrue if you are using the multiple entry point option of Rollup.For this feature to work,build.cssCodeSplit must be set totrue

Future release can have an advanced behavior where this options will be configured to true automatically by sniffinguser configurations.

If a CSS chunk is generated that's not imported by any JS chunk, a warning will be shown. To disable this warningsetsuppressUnusedCssWarning totrue.

styleId (string | function)

If you provide astring forstyleId param, the code of injection will set theid attribute of thestyle elementwith the value of the parameter provided. This is an example:

importcssInjectedByJsPluginfrom'vite-plugin-css-injected-by-js'exportdefault{plugins:[cssInjectedByJsPlugin({styleId:"foo"}),]}

The output injected into the DOM will look like this example:

<head><styleid="foo">/* Generated CSS rules */</style></head>

If you provide afunction forstyleId param, it will run that function and return a string. It's especially usefulif you userelativeCSSInjection and want unique styleIds for each file.

importcssInjectedByJsPluginfrom'vite-plugin-css-injected-by-js'exportdefault{plugins:[cssInjectedByJsPlugin({styleId:()=>`foo-${Math.random()*100}`}),]}
<head><styleid="foo-1234">/* Generated CSS rules */</style><styleid="foo-4321">/* Generated CSS rules */</style></head>

topExecutionPriority (boolean)

The default behavior adds the injection of CSS before your bundle code. If you providetopExecutionPriority equalto:false the code of injection will be added after the bundle code. This is an example:

importcssInjectedByJsPluginfrom'vite-plugin-css-injected-by-js'exportdefault{plugins:[cssInjectedByJsPlugin({topExecutionPriority:false}),]}

useStrictCSP (boolean)

TheuseStrictCSP configuration option adds a nonce to style tags basedon<meta property="csp-nonce" content={{ nonce }} />. See the followinglink formore information.

This is an example:

importcssInjectedByJsPluginfrom'vite-plugin-css-injected-by-js'exportdefault{plugins:[cssInjectedByJsPlugin({useStrictCSP:true}),]}

The tag<meta property="csp-nonce" content={{ nonce }} /> (nonce should be replaced with the value) must be present inyour html page. Thecontent value of that tag will be provided to thenonce property of thestyle element thatwill be injected by our default injection code.

Contributing

When you make changes to plugin locally, you may want to build the js from the typescript file of the plugin.

Here the guidelines:

Install

npm install

Testing

npm run test

Build plugin

npm run build

SeeCONTRIBUTING.md for more information.

A note for plugin-legacy users

At first the plugin supported generating the CSS injection code also in the legacy files generated bytheplugin-legacy. Since the plugin-legacy injectsthe CSS code fordifferent reasons, this plugin no longer has theplugin-legacy support code. If the code of the plugin-legacy changes an update to this plugin may occur.

About

A Vite plugin that takes the CSS and adds it to the page through the JS. For those who want a single JS file.

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks


[8]ページ先頭

©2009-2025 Movatter.jp