| 1 |
/** |
| 2 |
* @license |
| 3 |
* Copyright 2024 Google LLC |
| 4 |
* SPDX-License-Identifier: BSD-3-Clause |
| 5 |
*/ |
| 6 |
|
| 7 |
import {CSSStyleSheet} from './index.js'; |
| 8 |
|
| 9 |
try { |
| 10 |
// Detect whether the environment supports importing CSS files. |
| 11 |
const inlineCSS = 'data:text/css;base64,cHt0b3A6MDt9'; |
| 12 |
const cssImportsSupported = await import(inlineCSS, {with: {type: 'css'}}) |
| 13 |
.then(() => true) |
| 14 |
.catch(() => false); |
| 15 |
|
| 16 |
// Avoid breaking non-Node.js environments by checking for the |
| 17 |
// existance of register on the node:module import. |
| 18 |
const nodeModule = cssImportsSupported ? null : await import('node:module'); |
| 19 |
if (nodeModule && 'register' in nodeModule.default) { |
| 20 |
// Register the CSSStyleSheet polyfill in the global scope |
| 21 |
// in order for the hook to pick it up correspondingly when generating |
| 22 |
// code for CSS imports. |
| 23 |
// This also avoid breaking the serialization in packages/reactive-element/src/css-tag.ts |
| 24 |
// as the symbol will be available in the global scrope on evaluation. |
| 25 |
globalThis.CSSStyleSheet ??= CSSStyleSheet; |
| 26 |
/** |
| 27 |
* This module registers a Node.js Hook for loading CSS |
| 28 |
* files as CSSStyleSheet instances. |
| 29 |
* |
| 30 |
* @example |
| 31 |
* |
| 32 |
* ```ts |
| 33 |
* import styles from 'my-styles.css' with {type: 'css'}; |
| 34 |
* ``` |
| 35 |
* |
| 36 |
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import/with |
| 37 |
* @see https://nodejs.org/api/module.html#customization-hooks |
| 38 |
*/ |
| 39 |
nodeModule.default.register('./lib/css-hook.js', { |
| 40 |
parentURL: import.meta.url, |
| 41 |
}); |
| 42 |
} |
| 43 |
} catch { |
| 44 |
/* empty */ |
| 45 |
} |