整个插件就是在vite不同的生命周期中干不同的事情
手写vite-alias其实就是抢在vite.config.js配置文件执行之前,去改写vite.config.js配置文件。
项目根目录下src中建立plugins文件夹,在建立ViteAlias.js文件
// 必须给vite返回一个对象const fs = require("fs");
const path = require("path");function diffDirAndFile(dirFilesArr = [], basePath = "") {const result = {dirs: [],files: [],};dirFilesArr.forEach((name) => {const curFileState = fs.statSync(path.resolve(__dirname, basePath + "/" + name));const isDir = curFileState.isDirectory();if (isDir) {result.dirs.push(name);} else {result.files.push(name);}});return result;
}function getTotalSrcDir(keyName) {// 获取这个目录下的所有文件及文件夹console.log("====", path.resolve(__dirname, "../"));// 当前是在plugins文件夹目录下,/vite/src/plugins 所以拼接的时候需要往上返一层const result = fs.readdirSync(path.resolve(__dirname, "../"));const diffResult = diffDirAndFile(result, "../");const resolveAliasObj = {};diffResult.dirs.forEach((dirName) => {const key = `${keyName}${dirName}`;const absPath = path.resolve(__dirname, "../" + dirName);resolveAliasObj[key] = absPath;});return resolveAliasObj;
}module.exports = ({ keyName = "@" } = {}) => {return {/**** @param {*} config 目前vite.config.js 离的配置文件,只是拿到里面内容,不去执行配置文件* @param {*} env 有两个参数mode(表示是生产还是开发环境),command(执行的是dev还是build)*/config(config, env) {const resolveAliasObj = getTotalSrcDir(keyName);return {// 在这里需要返回一个resolve出去,将src下面的所有文件进行别名控制resolve: {alias: resolveAliasObj,},};},};
};
vite.config.js配置文件中引用
import { defineConfig } from "vite";
const MyVite = require("./src/plugins/Vitealias.js");
export default defineConfig({envPrefix: "ENV_",plugins: [MyVite()],
});