/**
* @description: vite插件
* 通过vite.config.js 返回出去的配置对象,以及我们在插件config的生命周期中返回的对象,都不是最终的一个配置对象
* vite 会把这几个配置对象进行一个 merge 合并
*/
const fs = require("fs");
const path = require("path");
function diffDirAndFile(arr = [], basePath = "") {
const result = {
dirs: [],
files: [],
};
arr.forEach((name) => {
const currentFileStat = fs.statSync(
path.resolve(__dirname, `${
basePath}/${
name}`)
);
const isDirectory = currentFileStat.isDirectory();
if (isDirectory) {
result.dirs.push(name);
} else {
result.files.push(name);
}
});
return result;
}
function getDir(keyName) {
const basePath = "../../src";
const result = fs.readdirSync(path.resolve(__dirname, basePath));
const diffResult = diffDirAndFile(result, basePath);
const resolveAlias = {
};
diffResult.dirs.forEach((dirName) => {
const key = `${
keyName}${
dirName}`;
const absolutePath = path.resolve(__dirname, `${
basePath}/${
dirName}`);
resolveAlias[key] = absolutePath;
});
return resolveAlias;
}
// realization alias plugin
module.exports = ({
keyName = "@" } = {
}) => {
return {
// config:当前的配置对象
// env: 当前环境信息 { mode: "development", command: "serve" }
config(config, env) {
// 此时的 config 只是 Vite 传入的配置文件,并没有执行
// Config 函数可以返回一个对象,这个对象是部分的vite config配置【其实就是需要修改的那一部分】
const aliasRes = getDir(keyName);
return {
// 读取目录
resolve: {
alias: aliasRes,
},
};
},
};
};
Vite plugins学习之手写 alias 插件
猜你喜欢
转载自blog.csdn.net/weixin_56650035/article/details/141223795
今日推荐
周排行