Skip to content

Commit 17e8b88

Browse files
committed
reduced inject boilerplate
1 parent 1961e6b commit 17e8b88

1 file changed

Lines changed: 11 additions & 1 deletion

File tree

src/index.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@ import { createFilter } from "@rollup/pluginutils";
22
import path from "path";
33
import fs from "fs";
44

5+
const INJECT_VIRTUAL_ID = "\0virtual:inject";
6+
const INJECT_UTIL = `export function __inject(css){if(typeof document != "undefined")document.head.appendChild(document.createElement("style")).textContent=css;}`;
7+
58
export default (options = {}) => {
69
if (!options.transform) options.transform = (code) => code;
710

@@ -64,6 +67,8 @@ export default (options = {}) => {
6467
name: "import-css",
6568

6669
resolveId(source, importer) {
70+
if (source == INJECT_VIRTUAL_ID) return INJECT_VIRTUAL_ID;
71+
6772
if (source.endsWith(".css") && (source.startsWith(".") || source.startsWith("/"))) {
6873
(imports[importer] = imports[importer] ?? []).push(source);
6974
return { id: path.resolve(path.dirname(importer), source) };
@@ -72,6 +77,11 @@ export default (options = {}) => {
7277
return null;
7378
},
7479

80+
/* load virtual modules for inline utilities */
81+
load(id) {
82+
if (id == INJECT_VIRTUAL_ID) return INJECT_UTIL;
83+
},
84+
7585
/* convert the css file to a module and save the code for a file output */
7686
async transform(code, id) {
7787
if (!filter(id)) return;
@@ -96,7 +106,7 @@ export default (options = {}) => {
96106
/* if inject is enabled, we want to simply inject the stylesheet into the document head */
97107
if (options.inject) {
98108
return {
99-
code: `if(typeof document!=="undefined")document.head.appendChild(document.createElement("style")).textContent=${JSON.stringify(transformedCode)};`,
109+
code: `import { __inject } from "${INJECT_VIRTUAL_ID}";__inject(${JSON.stringify(transformedCode)});`,
100110
map: null
101111
};
102112
}

0 commit comments

Comments
 (0)