1、配置 vite.config.ts修改文件别名
  1. vite.config.ts 文件,配置别名
-- vite.config.ts --

import { defineConfig } from 'vite'
// 1. commonjs 需要改为 esmoule引入
// 2. 需要安装 @types/node
import { resolve } from 'path'; 
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [
      {
        find: '@',                                   // 别名
        replacement: resolve(__dirname, 'src'),      // 别名对应地址
      },
      {
        find: 'components',
        replacement: resolve(__dirname, 'src/components'),
      }
    ]
  }
})
  1. 安装 @types/node 模块解决使用 import 引入nodejspath 模块 报错问题
npm i @types/node -D
2、配置tsconfig.json文件
  1. 通过 步骤1 设置别名之后,ts解析出现问题,如下图
  2. 需要配置 tsconfig.json设置 baseUrlpaths 属性
-- tsconfig.json --

{
  "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

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注