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.ts 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: press Fn1 and type "reload with extensions disabled", re-enabling extensions from the popup.
Now try to import
import MyComponent from "Components/MyComponent";
// if you have the export of the component in the index.ts of the components folder
import { MyComponent } from "Components";