配置模块路径别名
在 Vite 中支持模块路径别名自定义,参考文档。
基本配置
需要加入 path
依赖:
shell
yarn add path
shell
npm install path
在vite.config.ts
中配置:
ts
import { defineConfig } from 'vite'
import path from 'path'
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
})
在 ts 项目中进行配置
在 ts 模块中加载 node 核心模块需要安装 node 的类型补充模块@types/node
。
shell
yarn add -D @types/node
shell
npm install -D @types/node
注意:
如果没有安装该模块的话,上述配置中直接使用__dirname
会报错:cannot find name __dirname
。
还需要在tsconfig.json
中做如下配置:
json
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
使用示例
js/ts
js
import xxx from '@/api/user.js'
ts
import xxx from '@/api/user.ts'
html
html
<img src="@/assets/logo.png" />
css
css
@import url('@/styles/index.scss');
div {
background: url('@/assets/logo.png');
}