htmelt
Version:
Bundle your HTML assets with Esbuild and LightningCSS. Custom plugins, HMR platform, and more.
94 lines (92 loc) • 2.52 kB
JavaScript
import {
buildCSSFile
} from "./chunk-Q2H5B2YZ.mjs";
import {
esbuildBundles
} from "./chunk-26E6E5EJ.mjs";
import "./chunk-SGZXFKQT.mjs";
// src/plugins/cssCodeSplit.mts
import { fileToId, idToUri, md5Hex } from "@htmelt/plugin";
var cssCodeSplit = (config, flags) => {
config.esbuild.plugins.push({
name: "esbuild-plugin-inline-css",
setup(build) {
build.onLoad({ filter: /\.css$/ }, async (args) => {
const css = await buildCSSFile(args.path, config, flags);
return {
loader: "css",
contents: css.code
};
});
build.onTransform({ filter: /\.css$/ }, (args) => {
if (new URLSearchParams(args.suffix).has("raw")) {
return null;
}
if (!flags.watch) {
const bundle = esbuildBundles.get(build.initialOptions);
if (bundle) {
bundle.injectedStyles ||= [];
bundle.injectedStyles.push(args.code);
return {
loader: "js",
code: "export {}"
};
}
}
return {
loader: "js",
code: getCSSInjectionScript(
args.code,
args.path,
args.namespace,
config,
flags
)
};
});
}
});
};
function getCSSInjectionScript(code, file, namespace, config, flags) {
const id = fileToId(file, namespace);
config.registerCssEntry?.(id, code, "js");
const jsArgs = [
`"${md5Hex(file).slice(0, 12)}"`,
"`" + (flags.minify ? "" : "\n") + code.replace(/[\\`]/g, "\\$&") + "`"
];
let jsModule;
if (flags.watch) {
const id2 = fileToId(
namespace === "file" ? config.getBuildPath(file) : file,
namespace
);
const url = new URL(idToUri(id2), config.server.url);
jsModule = `(${injectStyleTag_DEV})(${jsArgs}, "${url.href}")`;
} else {
jsModule = `(${injectStyleTag})(${jsArgs})`;
}
return jsModule;
}
var injectStyleTag = (id, css) => {
if (!document.getElementById(id)) {
const style = document.createElement("style");
style.id = id;
style.textContent = css;
document.head.appendChild(style);
}
};
var injectStyleTag_DEV = (id, css, href) => {
let style = document.getElementById(id);
if (style) {
style.textContent = css;
} else {
style = document.createElement("style");
style.id = id;
style.textContent = css;
style.dataset.href = href;
document.head.appendChild(style);
}
};
export {
cssCodeSplit
};