forked from hyrious/esbuild-plugin-style
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
64 lines (54 loc) · 1.91 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import type { BuildOptions, Charset, Plugin } from "esbuild";
import sassPlugin from "esbuild-sass-plugin";
export interface StylePluginOptions {
/**
* whether to minify the css code.
* @default true
*/
minify?: boolean;
/**
* css charset.
* @default 'utf8'
*/
charset?: Charset;
}
// https://github.com/evanw/esbuild/issues/20#issuecomment-802269745
export function inlineSass({ minify = true, charset = "utf8" }: StylePluginOptions = {}): Plugin {
let esbuild_shim: typeof import("esbuild") | undefined;
return {
name: "inlineSass",
setup({ onResolve, onLoad, esbuild }) {
const opt: BuildOptions = { logLevel: "silent", bundle: true, write: false, charset, minify };
const require_esbuild = () => esbuild || (esbuild_shim ||= require("esbuild"));
onLoad({ filter: /\.s[a|c]ss$/ }, async args => {
const { errors, warnings, outputFiles } = await require_esbuild().build({
entryPoints: [args.path],
plugins: [sassPlugin()],
...opt,
});
const css = outputFiles![0].text.trimEnd();
return {
errors,
warnings,
contents: `import { inject_style } from "__style_helper__"\ninject_style(${JSON.stringify(css)})`,
};
});
onResolve({ filter: /^__style_helper__$/ }, () => {
return { path: "index.js", namespace: "style-helper" };
});
onLoad({ filter: /.*/, namespace: "style-helper" }, () => ({
contents:
`export function inject_style(text) {\n` +
` if (typeof document !== 'undefined') {\n` +
` var style = document.createElement('style')\n` +
` var node = document.createTextNode(text)\n` +
` style.appendChild(node)\n` +
` document.head.appendChild(style)\n` +
` }\n` +
`}`,
}));
},
};
}
export const inlineScss = inlineSass;
export default inlineSass;