vite-bolt/plugin/build/autocss.ts
2023-02-01 17:52:53 +08:00

50 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* css 分包自动引入到rollup 打包后的 组件 index.js 中
* e.g Buttom/index.js
* before import './index.less'
* after import './index.css'
*/
import cpy from "cpy";
import { resolve, dirname } from "path";
import { promises as fs } from "fs";
import less from "less";
import glob from "fast-glob";
const rootPath = process.cwd();
const sourceDir = resolve(rootPath, "src");
//lib文件目录
const targetLib = resolve(rootPath, "dist/ui");
//src目录
const srcDir = resolve(rootPath, "src");
const buildLess = async () => {
//直接将less文件复制到打包后目录
await cpy([`${sourceDir}/**/*.less`], targetLib);
//获取打包后.less文件目录(lib和es一样)
const lessFiles = await glob("**/*.less", { cwd: srcDir, onlyFiles: true });
//遍历含有less的目录
for (let path in lessFiles) {
const filePath = `${srcDir}/${lessFiles[path]}`;
//获取less文件字符串
const lessCode = await fs.readFile(filePath, "utf-8");
//将less解析成css
const code = await less.render(lessCode, {
//指定src下对应less文件的文件夹为目录
paths: [srcDir, dirname(filePath)],
});
//拿到.css后缀path
const cssPath = lessFiles[path].replace(".less", ".css");
//将css写入对应目录
await fs.writeFile(resolve(targetLib, cssPath), code.css);
}
};
buildLess();