DEV Community

Cover image for How to use absolute Imports using React with Ts and Vite
Abdeldjalil Hachimi
Abdeldjalil Hachimi

Posted on • Updated on

How to use absolute Imports using React with Ts and Vite

today I am going to talk about How to use absolute Imports using React with Ts and Vite

as you can see here I am using ... to find the path of components in order to use them, it looks fine since I do not have deep path.

Image description

to sum up in order to avoid it you can easily use this in your
tsconfig.json

"compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "~/*": ["./*"]
    },
}
Enter fullscreen mode Exit fullscreen mode

Image description

and after that go to vite.config.ts

  resolve: {
    alias: {
      '~': path.resolve(__dirname, 'src'),
    },
  },
Enter fullscreen mode Exit fullscreen mode

Image description

and it's done

Thanks for reading this article and if you have any suggestions you are welcome

Top comments (7)

Collapse
 
triethuynh2301 profile image
Triet M Huynh

Thank you so much! This is really helpful.

Collapse
 
jalalbmnf profile image
jalalbmnf

Easier

export default defineConfig({
resolve: {
alias: [{ find: "@", replacement: "/src" }],
},
plugins: [react()],
});

Collapse
 
israeldv profile image
Israel Moreno

Good Article ! Thanks for your post !

Collapse
 
evcorona profile image
veroxcrown

Thank you for your post!! Clear and really helpful.

Collapse
 
eamonnprwalsh profile image
Eamonn Walsh

I have been unable to get this to work

with

"compilerOptions": {
"baseUrl": "./src",
"paths": {
"~/": ["./"]
},
}

On both

resolve: {
alias: {
'~': path.resolve(__dirname, 'src'),
},
},

and
resolve: {
alias: [{ find: "@", replacement: "/src" }],
},

Collapse
 
conduongphang profile image
Trần Quốc Việt

how i can do that on my project use .jsx file insteal .ts file ??

Collapse
 
nadeemshareef profile image
Nadeem Shareef

create a file name .jsconfig and you should be able to replicate the same.