如何在Vite中配置类似Webpack的根路径短路径导入
在Vite中实现短路径导入(替代冗长相对路径)
要在Vite中实现类似Webpack通过jsconfig.json设置baseUrl的短路径导入效果,分两步操作即可:
1. 配置Vite打包时的路径解析
修改项目根目录下的vite.config.js(TypeScript项目则为vite.config.ts),添加resolve配置,让Vite识别短路径对应的实际目录:
方式一:直接映射src为模块根目录(和Webpack baseUrl效果完全一致)
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import path from 'path' export default defineConfig({ plugins: [react()], resolve: { // 将src目录加入模块搜索路径,直接用`components/Appbar`即可导入 modules: [path.resolve(__dirname, 'src'), 'node_modules'] } })
方式二:使用别名(更通用,避免和第三方包重名)
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import path from 'path' export default defineConfig({ plugins: [react()], resolve: { alias: { // 把src目录映射为@,导入时用`@/components/Appbar`代替冗长路径 '@': path.resolve(__dirname, './src') } } })
2. 配置IDE路径提示(避免红色波浪线)
为了让VS Code等IDE正确识别短路径并提供代码提示,需要配置对应配置文件:
JavaScript项目(jsconfig.json)
在项目根目录创建或修改jsconfig.json:
- 如果用方式一(直接映射src):
{ "compilerOptions": { "baseUrl": "src" }, "include": ["src"] }
- 如果用方式二(@别名):
{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"] } }, "include": ["src"] }
TypeScript项目(tsconfig.json)
修改tsconfig.json的compilerOptions:
- 如果用方式一(直接映射src):
{ "compilerOptions": { "baseUrl": "./src", // 保留原有其他配置 }, "include": ["src"] }
- 如果用方式二(@别名):
{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"] }, // 保留原有其他配置 }, "include": ["src"] }
完成以上配置后,你就可以摆脱冗长的相对路径,像在Webpack中一样轻松导入文件了。
内容的提问来源于stack exchange,提问作者Islam Y-
相关产品推荐
相关产品推荐

