vite配置别名并处理报错:找不到模块“xxx”或其相应的类型声明方法详解

1、配置vite.config.ts文件

安装 “@types/node” 模块,用于处理别名不生效问题

npm i @types/node -D

修改 “vite.config.ts” 文件,配置别名

import { defineConfig } from 'vite'
import { resolve } from 'path';
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
 plugins: [vue()],
 resolve: {
 alias: [
 {
 find: '@', // 别名
 replacement: resolve(__dirname, 'src'), // 别名对应地址
 },
 {
 find: 'components',
 replacement: resolve(__dirname, 'src/components'),
 }
 ]
 }
})

2、配置tsconfig.json文件

  • 这一步是用来解决 “报错:找不到模块“xxx”或其相应的类型声明” 的
  • 配置 “baseUrl 和 paths” 项
  • paths 里的内容根据别名来进行相关配置
{
 "compilerOptions": {
 "target": "ESNext",
 "useDefineForClassFields": true,
 "module": "ESNext",
 "moduleResolution": "Node",
 "strict": true,
 "jsx": "preserve",
 "sourceMap": true,
 "resolveJsonModule": true,
 "isolatedModules": true,
 "esModuleInterop": true,
 "lib": ["ESNext", "DOM"],
 "skipLibCheck": true,
 "baseUrl": ".",
 "paths": {
 "@/*":["src/*"],
 "components":["src/components/*"],
 "_pinia/*":["src/pinia/*"]
 }
 },
 "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
 "references": [{ "path": "./tsconfig.node.json" }]
}

总结

作者:大橘为重¨原文地址:https://blog.csdn.net/weixin_53068161/article/details/126693499

%s 个评论

要回复文章请先登录注册