Code Monkey home page Code Monkey logo

vite-plugin-inject-css-to-js's Introduction

vite-plugin-inject-css-to-js

Combine this with the Vite 3+ build.cssCodeSplit CSS code splitting capability to build css into individual js files instead of using css links.

Install

Make sure your vite version is 3 or higher.

# pnpm
pnpm add -D vite-plugin-inject-css-to-js
# yarn
yarn add -D vite-plugin-inject-css-to-js
# npm
npm i -D vite-plugin-inject-css-to-js

Usage

// vite.config.js
import { defineConfig } from 'vite';

// 1. import the plugin
import { InjectCssToJsPlugin } from 'vite-plugin-inject-css-to-js';

export default defineConfig({
    plugins: [
        // 2. add it to the plugins list
        InjectCssToJsPlugin(),
    ],
});

Supports using the 'beforeInjectCss' hook to customize the return of your CSS code, such as in cases where a custom CDN domain exists.

// vite.config.js
import { defineConfig } from 'vite';

// 1. import the plugin
import { InjectCssToJsPlugin } from 'vite-plugin-inject-css-to-js';

export default defineConfig({
    plugins: [
        // 2. add it to the plugins list
        InjectCssToJsPlugin({
            beforeInjectCss: cssCode => {
                return JSON.stringify(cssCode)
                    .replace(/\/static\/images/g, '${window.cdnDomain}/static/images')
                    .replace(/^"|"$/g, '`');
            },
        }),
    ],
});

Q&A

Why can't I build all css files into js?

Since Vite vite:build-html plugin is executed before this plugin (i.e. enforce: pre is set by default), when this plugin generateBundle hook is executed, the html file has already been transformed, so it is not desirable to violently remove all the link css links on the html, and we can't rule out the scenarios where the plugin dynamically inserts link css links via transformIndexHtml hook. It is not desirable to violently remove all the link css links on html, we can't exclude the scenario that other plugins dynamically insert link css links through transformIndexHtml hook.

How transformIndexHtml hooks are implemented in vite:build-html plugin.

The vite:build-html plugin calls the resolveHtmlTransforms method to get all the transformIndexHtml hooks inside the plugin, which are classified as preHooks, normalHooks and postHooks.

If order: pre is set, it is classified as preHooks, if post is set, it is classified as postHooks, and if transformIndexHtml is a pure method, it is classified as normalHooks.

/** preHooks */
transformIndexHtml: {
    order: 'pre',
    handler: (html) => {
        return html;
    }
}

/** normalHooks */
transformIndexHtml() {}

/** postHooks */
transformIndexHtml: {
    order: 'post',
    handler: (html) => {
        return html;
    }
}

At this point, the vite:build-html plugin will call applyHtmlTransforms inside the transform hook to execute the preHooks, and then the generateBundle hook to execute the [... .normalHooks, . .postHooks] hooks. This also explains why we can't remove all css links from html by transformIndexHtml hook in this plugin, because other plugins may manually insert other css links inside transformIndexHtml hook.

How to get the path of the css external link referenced inside the html file?

Refer to Vite4 source code getCssTagsForChunk method to get the css external file name (i.e. final file path).

const cssTags: Set<string> = new Set();
const analyzedChunk: Map<OutputChunk, number> = new Map();
const getCssTagsForChunk = (chunk: OutputChunk, seen: Set<string> = new Set()) => {
    const tags: { filename: string }[] = [];
    if (!analyzedChunk.has(chunk)) {
        analyzedChunk.set(chunk, 1);
        chunk.imports.forEach(file => {
            const importee = ctx.bundle?.[file];
            if (importee?.type === 'chunk') {
                tags.push(...getCssTagsForChunk(importee, seen));
            }
        });
    }

    chunk.viteMetadata!.importedCss.forEach(file => {
        if (!seen.has(file)) {
            seen.add(file);
            tags.push({
                filename: file,
            });
        }
    });

    return tags;
};

Is it a concern that other plugins manually inject css files via the transformIndexHtml hook?

Personally, I don't need to pay attention to css files, because usually emitFile is used to create a file, and the path to the file will be available in the production package that is built.

License

MIT ยฉ Levix

vite-plugin-inject-css-to-js's People

Contributors

dependabot[bot] avatar levix avatar renovate[bot] avatar

Stargazers

 avatar  avatar

Watchers

 avatar

vite-plugin-inject-css-to-js's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm standard-version Available

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): replace dependency standard-version with commit-and-tag-version ^9.5.0
  • chore(deps): update dependency prettier to v3.3.3
  • chore(deps): update dependency rollup to v4.20.0
  • chore(deps): update dependency rollup-plugin-typescript-paths to v1.5.0
  • chore(deps): update dependency typescript to v5.5.4
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Errored

These updates encountered an error and will be retried. Click on a checkbox below to force a retry now.

  • chore(deps): update dependency tsup to v8.2.4

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

npm
package.json
  • clean-css ^5.3.2
  • @commitlint/cli ^18.0.0
  • @commitlint/config-conventional ^18.0.0
  • @rollup/plugin-typescript ^11.1.2
  • @types/clean-css ^4.2.6
  • @types/node ^20.4.2
  • husky ^9.0.0
  • lint-staged ^15.0.0
  • prettier ^3.0.0
  • rollup ^4.0.0
  • rollup-plugin-typescript-paths ^1.4.0
  • standard-version ^9.5.0
  • tsup ^8.0.0
  • typescript ^5.1.6
  • vite 5.1.5
  • vite >= 3

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.