Skip to content

Commit

Permalink
Merge pull request #1 from Levix/feat/add-beforeInjectCss-hook
Browse files Browse the repository at this point in the history
feat: add beforeInjectCss hook
  • Loading branch information
Levix authored Dec 29, 2023
2 parents 9b01fe6 + e2dde32 commit 499d732
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import type { BuildOptions, Plugin } from 'vite';
import { createLogger } from 'vite';
import CleanCSS from 'clean-css';

export function InjectCssToJsPlugin(): Plugin {
export function InjectCssToJsPlugin({
beforeInjectCss,
}: {
beforeInjectCss?: (cssCode: string) => string | Promise<string>;
} = {}): Plugin {
const logger = createLogger();

let buildConfig: BuildOptions | undefined;
Expand Down Expand Up @@ -143,9 +147,19 @@ export function InjectCssToJsPlugin(): Plugin {
}
} else {
const initialCode = chunk.code;
const originalCssCode = cssCode;
if (cssCode && typeof beforeInjectCss === 'function') {
cssCode = await beforeInjectCss(cssCode);
}
if (!cssCode || typeof cssCode !== 'string') {
logger.warn(
`The beforeInjectCss hook returns content that is not a string or is empty, reverting to the original content.`,
);
cssCode = JSON.stringify(originalCssCode.trim());
}
chunk.code =
`(function(){ try {var elementStyle = document.createElement('style'); elementStyle.appendChild(document.createTextNode(` +
`${JSON.stringify(cssCode.trim())}` +
`${cssCode}` +
`));document.head.appendChild(elementStyle);} catch(e) {console.error('style-injected-by-js', e);} })(); ` +
`${initialCode}`;
}
Expand Down

0 comments on commit 499d732

Please sign in to comment.