| 1 |
import {readFile} from 'node:fs/promises'; |
| 2 |
import type {LoadHook} from 'node:module'; |
| 3 |
|
| 4 |
/** |
| 5 |
* When an attempt is made to import a CSS file/module, code is |
| 6 |
* generated to read the corresponding file, add it to a CSSStyleSheet |
| 7 |
* instance and return that instance as the default export. |
| 8 |
* |
| 9 |
* This expects the CSSStyleSheet class to be available in the global scope. |
| 10 |
* See register-css-hook.ts for how this is registered in Node.js. |
| 11 |
* |
| 12 |
* https://nodejs.org/api/module.html#loadurl-context-nextload |
| 13 |
*/ |
| 14 |
export const load: LoadHook = async (url, context, nextLoad) => { |
| 15 |
if (context.importAttributes.type === 'css') { |
| 16 |
const content = await readFile(new URL(url), 'utf-8'); |
| 17 |
const code = ` |
| 18 |
const sheet = new CSSStyleSheet(); |
| 19 |
sheet.replaceSync(${JSON.stringify(content)}); |
| 20 |
export default sheet; |
| 21 |
`; |
| 22 |
return {format: 'module', shortCircuit: true, source: code}; |
| 23 |
} else if (new URL(url).pathname.endsWith('.css')) { |
| 24 |
try { |
| 25 |
return await nextLoad(url, context); |
| 26 |
} catch (e) { |
| 27 |
console.warn( |
| 28 |
`Tried to import ${url} without import attributes!\n` + |
| 29 |
`(e.g. use "import s from './a.css' with {type: 'css'}" instead of "import s from './a.css'")` |
| 30 |
); |
| 31 |
throw e; |
| 32 |
} |
| 33 |
} |
| 34 |
return await nextLoad(url, context); |
| 35 |
}; |