Reputation: 2076
I'm struggling to get absolute path to work in a Vite react-ts project.
Here's how I created the project
npm init @vitejs/app
npx: installed 6 in 1.883s
√ Project name: ... test-vite
√ Select a framework: » react
√ Select a variant: » react-ts
Then I added baseUrl to tsconfig.json based on the TS official doc:
{
"compilerOptions": {
"baseUrl": "./src",
...
followed by adding a simple component (T:\test-vite\src\components\Test.tsx)
import React from "react";
const Test = () => <h1>This is a Test.</h1>;
export default Test;
Finally I import the Test component in App.tsx
but it won't let me use absolute path:
import Test from "components/Test";
whereas if I use relative path, the app works in dev & build mode without any error:
import Test from "./components/Test";
How can I make absolute path work in the project?
Upvotes: 106
Views: 115572
Reputation: 425
I had to add paths
compiler option to the tsconfig.app.json
file instead of the tsconfig.json
file for my IDE to recognize.
"paths": {
"src/*": [
"./src/*"
],
}
Along with the resolve config for vite.config.ts
file.
resolve: {
alias: {
src: '/src',
},
},
Upvotes: 2
Reputation: 141
in vite.config.ts use this kind of src
import { defineConfig } from "vite"
import path from "path"
import react from "@vitejs/plugin-react"
import federation from "@originjs/vite-plugin-federation"
export default defineConfig({
base: "/",
resolve: {
alias: {
src: path.resolve(__dirname, "./src"),
},
},
plugins: [
react(),
federation({
name: "project name",
filename: "your main tsx file name",
exposes: {
"./App": "your main tsx file path",
},
shared: [
"react",
"react-dom",
"react-router-dom",
"@reduxjs/toolkit",
"react-error-boundary",
"react-redux",
"react-tooltip",
],
}),
],
build: {
target: "esnext",
sourcemap: process.env.NODE_ENV === "production" ? false : true,
minify: process.env.NODE_ENV === "production" ? true : false,
emptyOutDir: true,
},
})
Upvotes: 0
Reputation: 1504
this is just the an update from prev answers. I just merge the @Yuns and @Jashwant solution to make it work for me. You need to only update 2 parts
tsconfig.json
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"] // ==> dot before '/' is important
},
},
}
you can also find compilerOptions
in tsconfig.app.json
.
and vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});
if you see an error complaining about __dirname
just dev-install @types/node
yarn add -D @types/node
it shou;d work for "vite": "^5.4.0"
Upvotes: 1
Reputation: 3010
There are two problems here:
You only tell typescript how to resolve, but vite don't know how to build. So refer to the official document resolve.alias, maybe this is what you want:
// vite.config.ts
{
resolve: {
alias: [
{ find: '@', replacement: path.resolve(__dirname, 'src') },
],
},
// ...
}
You can import path like this (or any module under ./src
):
import Test from "@/components/Test";
import bar from "@/foo/bar"
Moreover, you can use vite plugin vite-tsconfig-paths
directly, it makes you don't have to manually configure resolve.alias
Follow the instructions below:
Install vite-tsconfig-paths
as dev dependency
Inject vite-tsconfig-paths
using the vite.config.ts module
import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'
export default defineConfig({
plugins: [tsconfigPaths()],
})
Upvotes: 216
Reputation: 2003
For me the issue was happening because baseURL and paths both were defined in tsconfig.json. Remove baseURL and it should work.
Upvotes: 0
Reputation: 391
here is what i write on gxanshu
To configure your app to use absolute import, you need to make some changes to the vite.config.js file, which is found at the root of your project directory.
Add the code below to the vite.config.js
file
resolve: {
alias: {
src: "/src",
},
},
like
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
// here add the absolute paths that you wanna add
src: "/src",
},
},
});
after changing this file you can able to import absolute paths in TypeScript files here is an example
import Button from "src/components/Button/Button"
but to get intelligence from your code editor like VS code you have to change tsconfig.json file
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"src/*": ["./src/*"],
}
}
}
in this way you can able to use absolute paths without any third party packages.
Upvotes: 3
Reputation: 785
For anyone not using TypeScript that wants to do the same, you can achieve this by installing a Rollup plugin.
npm install --save-dev rollup-plugin-includepaths
vite.config.js
import includePaths from "rollup-plugin-includepaths";
export default defineConfig({
plugins: [
react(),
includePaths({ paths: ["./"] })
]
})
Now you can import modules with a path like this…
import MyModule from "src/components/MyModule";
I prefer to use includePaths({ paths: ["./src"] })
to allow a simpler import, like import MyModule from "components/MyModule"
.
Upvotes: 0
Reputation: 2814
Step 1 - vite.config.ts
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react(),tsconfigPaths()],
});
Step 2 - tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"useDefineForClassFields": true,
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"baseUrl": "./src",
"paths": {
"@assets/*": ["./assets/*"],
"@components/*": ["./components/*"],
"@config/*": ["./config/*"],
"@hooks/*": ["./hooks/*"],
"@ioc/*": ["./ioc/*"],
"@pages/*": ["./pages/*"],
"@utils/*": ["./utils/*"]
},
"typeRoots": ["node_modules/@types", "./types"]
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.js", "src/**/*.jsx", "tests/**/*.ts", "tests/**/*.tsx"],
"exclude": ["node_modules", "dist"],
"references": [{ "path": "./tsconfig.node.json" }]
}
Step 3 - index.tsx
import React from 'react';
import HeaderCustom from '@components/header';
interface Props {
children?: React.ReactNode;
}
const Component: React.FC<Props> = ({ children, ...props }) => {
return (
<>
<HeaderCustom></HeaderCustom>
</>
)
}
export default Component;
Upvotes: 8
Reputation: 21
Try updating vite.config.ts file!
install vite-tsconfig-paths as dev dependency
import tsconfigPaths
add tsconfigPaths() to plugins
vite.config.ts
import tsconfigPaths from "vite-tsconfig-paths"
defineConfig({ ..., plugins: [..., tsconfigPaths()] })
Upvotes: 2
Reputation: 784
1) You need to install these packages:
npm i path
yarn add path
npm i @types/node
yarn add @types/node
npm i vite-tsconfig-paths
yarn add vite-tsconfig-paths
2) Then in the vite.config file:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';
import path from 'path';
export default defineConfig({
base: './',
resolve: {
alias: {
Components: path.resolve(__dirname, './src/components'),
Assets: path.resolve(__dirname, './src/assets'),
},
},
plugins: [react(), tsconfigPaths()],
});
3) And now we have to tell TS those same paths that we defined in the alias:
{
"compilerOptions": {
...,
"baseUrl": "./",
"paths": {
"src/*": [ "./src/*" ],
// We define this path for all files/folders inside
// components folder:
"Components/*": [ "./src/components/*" ],
// We define this path for the index.ts file inside the
// components folder:
"Components": [ "./src/components" ],
"Assets/*": [ "./src/assets/*" ],
"Assets": [ "./src/assets" ]
}
},
...
}
4) reload vscode: As the comment above said, press Fn1 and type "reload with extensions disabled", re-enabling extensions from the popup.
Now try to import
import Test from "components/Test";
it should work.
Upvotes: 3
Reputation: 53
For anyone who stucks after all required changes, you need to reload vscode. My config files:
tsconfig.json
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias: { '@': path.resolve(__dirname, './src') },
},
plugins: [react()],
});
In above code you need to have 2 libraries installed:
After configure your project files you need to reload vscode. To do that press ctrl + P and type ">reload with extensions disabled", after that you will get popUp to activate extensions again click it, and your absoulte path should work
If someone installed vite-tsconfig-paths library, you also need to reload the vscode, remember to import given library to vite.config.ts
export default defineConfig({ plugins: [react(), tsconfigPaths()] });
With package you get default 'components/File' import instead of '@components/File' import.
Upvotes: 1
Reputation: 1766
For anyone looking specifically to add the nice import "@/something-in-src"
syntax like Vue has with the latest (as of posting this answer) version of Vite + React + TypeScript, here's how I did it:
Make sure @types/node
is installed as a dev dependency. This didn't come with the latest version of Vite for me, and it will make "path"
and __dirname
throw an undefined error.
vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
resolve: {
alias: [{ find: "@", replacement: path.resolve(__dirname, "src") }],
},
plugins: [react()],
});
tsconfig.json
Add:
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
Upvotes: 0
Reputation: 928
import {...} from "src/foo/bar";
?I also came here through search results like user Maciej Krawczyk, but the @
part also wasn't what I was interested in. That user's answer helped me, but I had trouble with the path.resolve
part (ReferenceError because path
wasn't defined), so I used a slightly different approach:
vite.config.ts
export default defineConfig({
...
resolve: {
alias: {
src: "/src",
},
},
...
})
Vite's resolver considers the absolute path /src
to be from where the server is serving (see GH issue). So if you're running/building from the root of your project with src
as a top level directory -- which is pretty common -- this alias points Vite in the right direction.
tsconfig.json
{
"compilerOptions": {
...
"baseUrl": "./",
"paths": {
"src/*": [
"./src/*"
]
}
}
}
This is basically blindly following this StackOverflow answer. TypeScript needs to know that we have special resolving going on as well, otherwise TS will be freaked out about your non-existent src
package and not know where it should go looking. (Note: After I changed my TS config, VSCode didn't immediately pick up the change, so I was still getting warnings. I quit, re-opened, and had to wait ~15sec for the warnings to go away.)
Upvotes: 22
Reputation: 16697
I came here through search results, I was looking for something different, namely, how to do a simple absolute import like import { foo } from 'src/lib/foo.ts'
So if you have a /src directory that contains all code and want to use an absolute import path.
vite.config.ts
export default defineConfig({
...
resolve: {
alias: {
src: path.resolve('src/'),
},
}
})
tsconfig.json
{
"compilerOptions": {
...
"baseUrl": "./"
}
}
Note that this is a trick: src is an alias, so it appears like the path is absolute in Vite. If you have another directory in the root dir, adjacent to /src, you will need to add another alias for that directory.
Upvotes: 31
Reputation: 29025
@Yuns solutions works, but it shows error in vscode. And it was breaking auto-import in vs code.
To make it work in vscode and vite both, I added alias in both tsconfig and vite.config.
// tsconfig.json
{
"paths": {
"@/*": ["src/*"]
}
// ...
}
// vite.config.ts
{
resolve: {
alias: [{ find: '@', replacement: '/src' }],
},
// ...
}
Then, I could import like below (svelte app is in src
directory)
import Header from '@/components/Header.svelte
Upvotes: 27