Reputation: 93
I'm starting a project with React using latest Vite project template:
npm create vite@latest my-app -- --template react-ts
The template contains 3 tsconfig files.
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"]
}
Which of these files should I edit to configure the alias path? I tried to edit the tsconfig.app.json file adding these lines:
"baseUrl": "./src",
"paths": {
"@pages/*": ["./pages/*"]
}
This is my vite.config.ts file:
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,
},
});
If I try to import a page like this:
import { Dashboard } from "@pages";
I get error: Cannot find module '@pages' or its corresponding type declarations.
What am I doing wrong?
Thanks!
Upvotes: 0
Views: 309
Reputation: 2756
I recommend you use @/pages
instead of @pages
then use vite-tsconfig-paths and define the absolute paths in tsconfig
then in your vite config:
import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'
export default defineConfig({
plugins: [tsconfigPaths()],
})
Upvotes: 0
Reputation: 1711
One solution would be to remove the @pages
alias and replace its references in imports by "@/pages"
, since they seem to be located directly under ./src
. An other, since @
could be resolved prior in @pages
, is to indicate the explicit replacement:
root: "./src",
resolve: {
alias:[
{ find: '@pages', replacement: resolve(__dirname,"/pages/") },
{ find: '@', replacement: resolve(__dirname,"/") }
]
},
Upvotes: 0