Skip to content

Instantly share code, notes, and snippets.

@luciaaldana
Last active February 2, 2023 12:25
Show Gist options
  • Save luciaaldana/7343c77b56e02a1ab7ed2903c01a843d to your computer and use it in GitHub Desktop.
Save luciaaldana/7343c77b56e02a1ab7ed2903c01a843d to your computer and use it in GitHub Desktop.
Absolute path in Vite project React TS (alias)

Absolute path in Vite project React TS (alias)

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";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment