UNPKG

1.67 kBJavaScriptView Raw
1import { promises as fs } from 'fs';
2function getInjectorCode(name, code) {
3 return `
4/** SNOWPACK INJECT STYLE: ${name} */
5function __snowpack__injectStyle(css) {
6 const headEl = document.head || document.getElementsByTagName('head')[0];
7 const styleEl = document.createElement('style');
8 styleEl.type = 'text/css';
9 if (styleEl.styleSheet) {
10 styleEl.styleSheet.cssText = css;
11 } else {
12 styleEl.appendChild(document.createTextNode(css));
13 }
14 headEl.appendChild(styleEl);
15}
16__snowpack__injectStyle(${JSON.stringify(code)});\n`;
17}
18/**
19 * rollup-plugin-css
20 *
21 * Support installing any imported CSS into your dependencies. This isn't strictly valid
22 * ESM code, but it is popular in the npm ecosystem & web development ecosystems. It also
23 * solves a problem that is difficult to solve otherwise (referencing CSS from JS) so for
24 * those reasons we have added default support for importing CSS into Snowpack v2.
25 */
26export function rollupPluginCss() {
27 return {
28 name: 'snowpack:rollup-plugin-css',
29 resolveId(source, importer) {
30 if (!source.endsWith('.css')) {
31 return null;
32 }
33 return this.resolve(source, importer, { skipSelf: true }).then((resolved) => {
34 return resolved || null;
35 });
36 },
37 async load(id) {
38 if (!id.endsWith('.css')) {
39 return null;
40 }
41 const code = await fs.readFile(id, { encoding: 'utf8' });
42 const humanReadableName = id.replace(/.*node_modules[\/\\]/, '').replace(/[\/\\]/g, '/');
43 return getInjectorCode(humanReadableName, code);
44 },
45 };
46}