diff --git a/.changeset/tiny-shoes-change.md b/.changeset/tiny-shoes-change.md new file mode 100644 index 000000000..d5ae1a8ec --- /dev/null +++ b/.changeset/tiny-shoes-change.md @@ -0,0 +1,5 @@ +--- +'@vanilla-extract/esbuild-plugin': patch +--- + +feat: esbuild inline css diff --git a/packages/esbuild-plugin/src/index.ts b/packages/esbuild-plugin/src/index.ts index c86aa777b..0670587c1 100644 --- a/packages/esbuild-plugin/src/index.ts +++ b/packages/esbuild-plugin/src/index.ts @@ -9,6 +9,7 @@ import { vanillaExtractTransformPlugin, IdentifierOption, CompileOptions, + hash, } from '@vanilla-extract/integration'; import type { Plugin } from 'esbuild'; @@ -16,6 +17,7 @@ const vanillaCssNamespace = 'vanilla-extract-css-ns'; interface VanillaExtractPluginOptions { outputCss?: boolean; + inlineCss?: boolean; /** * @deprecated Use `esbuildOptions.external` instead. */ @@ -27,6 +29,7 @@ interface VanillaExtractPluginOptions { } export function vanillaExtractPlugin({ outputCss, + inlineCss, externals = [], runtime = false, processCss, @@ -56,16 +59,34 @@ export function vanillaExtractPlugin({ if (typeof processCss === 'function') { source = await processCss(source); } + if (inlineCss) { + const id = `css_${hash(source)}`; + const injectStyles = String.raw` + var css = ${JSON.stringify(source)} + var style = document.getElementById('${id}'); + if (!style) { + style = document.createElement("style"); + style.id = "${id}"; + style.setAttribute("type", "text/css"); + document.head.appendChild(style); + } + style.innerHTML = css; + ` + return { + contents: injectStyles, + loader: 'js' + } + } else { + const rootDir = build.initialOptions.absWorkingDir ?? process.cwd(); - const rootDir = build.initialOptions.absWorkingDir ?? process.cwd(); - - const resolveDir = dirname(join(rootDir, fileName)); + const resolveDir = dirname(join(rootDir, fileName)); - return { - contents: source, - loader: 'css', - resolveDir, - }; + return { + contents: source, + loader: 'css', + resolveDir, + }; + } }, );