no-bundle构建工具(下)
接下来完成
- CSS 编译插件
- 静态资源加载插件
- 模块依赖图开发,并在 transform 中间件中接入
- HMR 服务端代码开发
- HMR 客户端代码开发
CSS 编译插件
ts
import { readFile } from "fs-extra";
import { Plugin } from "../plugin";
export function cssPlugin(): Plugin {
return {
name: "m-vite:css",
load(id) {
// 加载
if (id.endsWith(".css")) {
return readFile(id, "utf-8");
}
},
// 转换逻辑
async transform(code, id) {
if (id.endsWith(".css")) {
// 包装成 JS 模块
const jsContent = `
const css = "${code.replace(/\n/g, "")}";
const style = document.createElement("style");
style.setAttribute("type", "text/css");
style.innerHTML = css;
document.head.appendChild(style);
export default css;
`.trim();
return {
code: jsContent,
};
}
return null;
},
};
}
小结
拦截css文件,由resolve插件解析插件,自定义js加载css逻辑,即创建style标签,插入文档