unplugin-lightningcss
Version:
Lightning CSS integration for Vite, Rollup, esbuild, Webpack, Vue CLI, and more.
53 lines (51 loc) • 1.79 kB
JavaScript
import { Buffer } from "node:buffer";
import { readFile } from "node:fs/promises";
//#region src/core/transform.ts
const postfixRE = /[#?].*$/s;
function cleanUrl(url) {
return url.replace(postfixRE, "");
}
async function transformCss(id, code, options, asString) {
const filename = cleanUrl(id);
const { transform } = await import("lightningcss");
const result = transform({
...options,
filename,
code: Buffer.from(code)
});
let resultCode = result.code.toString();
if (asString) resultCode = `export default ${JSON.stringify(resultCode)}`;
return {
code: resultCode,
map: asString ? void 0 : "map" in result ? result.map?.toString() : void 0,
moduleType: asString ? "js" : "css"
};
}
async function transformCssModule(id, options) {
const actualId = id.replace(/\?css_module$/, "");
const code = await readFile(actualId, "utf8");
const filename = cleanUrl(actualId);
const { transform } = await import("lightningcss");
const res = transform({
cssModules: true,
...options,
filename,
code: Buffer.from(code)
});
const compiledId = actualId.replaceAll("\\", "/").replace(/\.module\.css$/, ".module_built.css");
const classes = Object.fromEntries(Object.entries(res.exports ?? {}).map(([key, value]) => [key, value.name]));
let exports = `const classes = ${JSON.stringify(classes)}\nexport default classes\n`;
const i = 0;
for (const key of Object.keys(classes)) {
const sanitizedKey = `_${key.replaceAll(/\W/g, "_")}${i}`;
exports += `\nconst ${sanitizedKey} = classes[${JSON.stringify(key)}]\nexport { ${sanitizedKey} as ${JSON.stringify(key)} }\n`;
}
return {
code: res.code.toString(),
map: "map" in res ? res.map?.toString() : void 0,
id: compiledId,
exports
};
}
//#endregion
export { transformCssModule as n, transformCss as t };