viteesbuild

Use `compilerOptions.baseUrl` with Vite.js project?


I'm trying to migrate from Create React App to Vite.js, but I'm having issues with the import aliases.

In Create React App I have a jsconfig.json file with compilerOptions.baseUrl set to src, so that if I import Comp from 'components/MyComponent it gets automatically converted to a relative import that points to src/components/MyComponent.

I can't understand how to achieve the same with Vite.js and esbuild?


Solution

  • According to the comment, using config option root of vite and setting an alias is not an option.

    The solution presented here is to buid dynamicaly aliases.

    Assuming a folder hierarchy like the following :

    root_project
    │   README.md
    │   package.json    
    │
    └───resources
    │   │   index.html
    │   |   app.js
    │   |___components
    |   |   |
    |   |   |___ HelloWorld.svelte
    |   |
    │   │___assets
    |   |   |
    |   |   |___css
    |   |   |   |
    |   |   |   |___app.scss
    |   |   |   
    |   |___config
    |   |   |
    |   |   |___index.ts
    │   |
    └───node_modules
    
    

    in vite.config.js

    import { defineConfig } from 'vite'
    import path from 'path'
    import { readdirSync } from 'fs'
    
    const absolutePathAliases: { [key: string]: string } = {};
    // Root resources folder
    const srcPath = path.resolve('./resources/');
    // Ajust the regex here to include .vue, .js, .jsx, etc.. files from the resources/ folder
    const srcRootContent = readdirSync(srcPath, { withFileTypes: true }).map((dirent) => dirent.name.replace(/(\.ts){1}(x?)/, ''));
    
    srcRootContent.forEach((directory) => {
      absolutePathAliases[directory] = path.join(srcPath, directory);
    });
    
    export default defineConfig({
      root: 'resources',
      resolve: {
        alias: {
          ...absolutePathAliases
        }
      },
    
      build: {
        rollupOptions: {
          input: '/main.ts'
        }
      }
    });
    
    

    Now, you can include a component without changing your imports directive :

    import HelloWorld from 'components/HelloWorld.svelte'
    

    You can also include files directly from resources folder:

    import { foo } from 'config'
    

    Same for assets and other files under resources or global libs:

    import path from 'path'               // <--- global
    import { foo } from 'config'          // <--- resources
    import logoUrl from 'assets/logo.png' // <--- resources
    

    More info there: vite official doc