我正在使用最新的 Vite 项目模板使用 React 启动一个项目:
npm create vite@latest my-app -- --template react-ts
模板包含3个tsconfig文件。
tsconfig.json
{
"files": [],
"references": [
{"path": "./tsconfig.app.json"},
{"path": "./tsconfig.node.json"}
]
}
tsconfig.node.json
{
"compilerOptions": {
"composite": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true,
"noEmit": true
},
"include": ["vite.config.ts"]
}
tsconfig.app.json
{
"compilerOptions": {
"composite": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
我应该编辑以下哪些文件来配置别名路径?我尝试编辑 tsconfig.app.json 文件添加以下行:
"baseUrl": "./src",
"paths": {
"@pages/*": ["./pages/*"]
}
这是我的vite.config.ts文件:
import { AliasOptions, defineConfig } from "vite";
import path from "path";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
"@pages": path.resolve(__dirname, "src/pages"),
} as AliasOptions,
},
});
如果我尝试导入这样的页面:
import { Dashboard } from "@pages";
我收到错误:
Cannot find module '@pages' or its corresponding type declarations.
我做错了什么?
谢谢!
很多时候,这些交叉配置可能会非常令人困惑。 在您的情况下,您可能不需要将路径设置为
tsconfig.app.json
。
一种解决方案是删除 @pages
别名,并将导入中的引用替换为 "@/pages"
,因为它们似乎直接位于 ./src
下。另一个,由于 @
可以在 @pages
中提前解决,因此表示显式替换:
root: "./src",
resolve: {
alias:[
{ find: '@pages', replacement: resolve(__dirname,"/pages/") },
{ find: '@', replacement: resolve(__dirname,"/") }
]
},