1. vite-aliases的使用
vite-aliases可以帮助我们自动生成别名: 检测你当前目录下包括src在内的所有文件夹, 并帮助我们去生成别名
plugins: [
ViteAliases({
"@": "/**/src",
"@aseets": "/**/src/assets",
"@components": "/**/src/components",
})
]
src
assets
components
pages
store
utils
=====================================
[
{
find: '@',
replacement: '${your_project_path}/src'
},
{
find: '@assets',
replacement: '${your_project_path}/src/assets'
},
{
find: '@components',
replacement: '${your_project_path}/src/components'
},
{
find: '@pages',
replacement: '${your_project_path}/src/pages'
},
{
find: '@store',
replacement: '${your_project_path}/src/store'
},
{
find: '@utils',
replacement: '${your_project_path}/src/utils'
},
]
==========================================================
`src/components` -> `@components`
`src/pages/components` -> `@pagesComponents`
`src/test/new/partials/components` -> `@testNewPartialsComponents`
==========================================================
ViteAliases({
/**
* Relative path to the project directory
*/
dir: 'src',
/**
* Prefix symbol for the aliases
*/
prefix: '@',
/**
* Allow searching for subdirectories
*/
deep: true,
/**
* Search depthlevel for subdirectories
*/
depth: 1,
/**
* Creates a Logfile
* use `logPath` to change the location
*/
createLog: false,
/**
* Path for Logfile
*/
logPath: 'src/logs',
/**
* Create global project directory alias
*/
createGlobalAlias: true,
/**
* Turns duplicates into camelCased path aliases
*/
adjustDuplicates: false,
/**
* Used paths in JS/TS configs will now be relative to baseUrl
*/
useAbsolute: false,
/**
* Adds seperate index paths
* approach created by @davidohlin
*/
useIndexes: false,
/**
* Generates paths in IDE config file
* works with JS or TS
*/
useConfig: true,
/**
* Will generate Paths in tsconfig
* used in combination with `useConfig`
* Typescript will be auto detected
*/
dts: false,
/**
* Root path of Vite project
*/
root: process.cwd()
});
2.手写vite-aliases 原理
整个插件就是在vite的生命周期的不同阶段去做不同的事情
比方说vue和react会给你提供一些生命周期函数:
- created
- mounted
生命周期钩子
我们去手写Vite-aliases其实就是抢在vite执行配置文件之前去改写配置文件
通过vite.config.js 返回出去的配置对象以及我们在插件的config生命周期中返回的对象都不是最终的一个配置对象
vite会把这几个配置对象进行一个merge合并
{...defaultConfig, ...specifyConfig}
ViteAliases.js
// vite的插件必须返回给vite一个配置对象
const fs = require("fs");
const path = require("path");
function diffDirAndFile(dirFilesArr = [], basePath = "") {
const result = {
dirs: [],
files: []
}
dirFilesArr.forEach(name => {
// 我直接用异步的方式去写的
const currentFileStat = fs.statSync(path.resolve(__dirname, basePath + "/" + name));
console.log("current file stat", name, currentFileStat.isDirectory());
const isDirectory = currentFileStat.isDirectory();
if (isDirectory) {
result.dirs.push(name);
} else {
result.files.push(name);
}
})
return result;
}
function getTotalSrcDir(keyName) {
const result = fs.readdirSync(path.resolve(__dirname, "../src"));
const diffResult = diffDirAndFile(result, "../src");
console.log("diffResult", diffResult);
const resolveAliasesObj = {}; // 放的就是一个一个的别名配置 @assets: xxx
diffResult.dirs.forEach(dirName => {
const key = `${keyName}${dirName}`;
const absPath = path.resolve(__dirname, "../src" + "/" + dirName);
resolveAliasesObj[key] = absPath;
})
return resolveAliasesObj;
}
module.exports = ({
keyName = "@"
} = {}) => {
return {
config(config, env) {
// 只是传给你 有没有执行配置文件: 没有
console.log("config", config, env);
// config: 目前的一个配置对象
// production development serve build yarn dev yarn build
// env: mode: string, command: string
// config函数可以返回一个对象, 这个对象是部分的viteconfig配置【其实就是你想改的那一部分】
const resolveAliasesObj = getTotalSrcDir(keyName);
console.log("resolve", resolveAliasesObj);
return {
// 在这我们要返回一个resolve出去, 将src目录下的所有文件夹进行别名控制
// 读目录
resolve: {
alias: resolveAliasesObj
}
};
}
}
}
config 生命周期获取的参数