vite-tsconfig-paths

repository·master·Indexed 23 days ago

https://github.com/aleclarson/vite-tsconfig-paths

A Vite plugin that enables path aliasing by reading and applying the `paths` configuration from `tsconfig.json` files. It supports custom project discovery strategies (eager or lazy), root directory specification, and path resolution for non-TypeScript modules via the `loose` option or `allowJs` setting. Version 7.0.0-alpha.1.

Tokens
1.5K
Snippets
3
Records
9
Agent score
81%

What's inside vite-tsconfig-paths

  1. Understand TSConfig path mapping behavior

    master

    The plugin respects standard TypeScript configuration options:

    • allowJs: When true, path resolution extends to .astro, .vue, .svelte, .mdx, .mjs, .js, and .jsx files.
    • baseUrl: If defined, it is prepended to all bare imports and takes precedence over node_modules, matching TypeScript's behavior.
    • include/exclude: These glob patterns are respected using a lightweight glob-to-regex compiler.
  2. Enable path resolution for non-TypeScript modules

    master

    By default, the plugin only resolves imports for TypeScript and JavaScript files. To enable path resolution for other file types (e.g., .vue, .svelte, .mdx), you have two options:

    Option 1: Update tsconfig.json Set allowJs to true in your tsconfig.json:

    {
      "compilerOptions": {
        "allowJs": true
      }
    }

    Option 2: Use the loose plugin option Pass loose: true to the tsconfigPaths constructor in your Vite config. This is useful if you want to avoid modifying your tsconfig.json or if allowJs does not resolve the issue.

  3. Setup vite-tsconfig-paths in Vite

    master

    To use the plugin, follow these steps:

    1. Ensure your project has "type": "module" in package.json, or rename your Vite config to vite.config.mjs or vite.config.mts.
    2. Import and add tsconfigPaths() to your plugins array in vite.config.ts.

    Note: CSS imports are not supported due to Vite limitations.

    import { defineConfig } from 'vite'
    import tsconfigPaths from 'vite-tsconfig-paths'
    
    export default defineConfig({
      plugins: [tsconfigPaths()],
    })
  4. Understand project discovery strategies

    master

    The plugin uses two strategies for finding and parsing tsconfig.json files via the projectDiscovery option:

    Eager Strategy ('eager')

    • Behavior: All tsconfig.json files are loaded and parsed immediately when the plugin initializes.
    • Limitation: Files are not reloaded if they are edited during development.
    • Default: This is the default setting.

    Lazy Strategy ('lazy')

    • Behavior: tsconfig.json files are parsed only when an import is encountered in a module that exists within the directory (or a subdirectory) of a discovered tsconfig.json.
    • Best Practice: Use the projects option alongside 'lazy' to ensure project references are correctly discovered.
    • Warning: Do not use 'lazy' if your tsconfig.json files use ../* paths in their include or files arrays, as the plugin may fail to discover the config file.
  5. Troubleshoot vite-tsconfig-paths resolution issues

    master

    If path resolution is not working as expected, you can use the following methods to debug:

    1. Environment Variable: Run Vite with the DEBUG variable set to see output:
      DEBUG=vite-tsconfig-paths yarn vite
    2. Log File: Enable detailed logging by setting logFile: true in the plugin configuration. This writes a full resolution trace to vite-tsconfig-paths.log in your working directory.
  6. Configure vite-tsconfig-paths plugin options

    master

    The tsconfigPaths plugin accepts several options to customize behavior. It is recommended to start without options and only add them as needed.

    OptionTypeDescription
    projectDiscovery"eager" | "lazy"Controls how tsconfigs are loaded. Default is "eager". In "lazy" mode, files are only scanned when an import is encountered in a supported module.
    rootstringThe directory to search for tsconfig.json files.
    projectsstring[]Explicit paths to tsconfig files (relative to root). Use root instead if possible.
    loosebooleanIf true, any file transpiled to JS will have its imports resolved. Disables strictness for TS/JS importers.
    importerFilter(importer: string) => booleanA function to filter which files have their imports resolved. Has no effect if loose is true.
    parseNativebooleanUses tsconfck.parseNative to delegate loading to the TypeScript compiler. Warning: Can slow startup by ~600ms.
    ignoreConfigErrorsbooleanIf true, parsing errors in tsconfig files are ignored. Useful for monorepos.
    logFilestring | booleanEnables detailed resolution logs. Pass true for vite-tsconfig-paths.log in the working directory, or provide a custom path.
    skip(dir: string) => booleanA function to determine which directories to skip during search (e.g., to improve performance in large monorepos).
    import { defineConfig } from 'vite'
    import tsconfigPaths from 'vite-tsconfig-paths'
    
    export default defineConfig({
      plugins: [
        tsconfigPaths({
          /* options go here */
        }),
      ],
    })
  7. Use the vite-tsconfig-paths plugin

    master

    The vite-tsconfig-paths plugin allows Vite to resolve module imports using the paths configuration defined in your tsconfig.json.

    To use it, import the default export from vite-tsconfig-paths and add it to your vite.config.ts plugins array. You can optionally pass a PluginOptions object to configure its behavior.

  8. Configure vite-tsconfig-paths via PluginOptions

    master

    The plugin accepts an optional PluginOptions object. Key configuration capabilities include:

    • root: Specifies a custom project root relative to the Vite config root.
    • logFile: Enables logging.
      • Pass true to log to a default file named vite-tsconfig-paths.log.
      • Pass a string to specify a custom log file path.
    • skip: A function used to skip specific directories during resolution. By default, .git and node_modules are skipped. You can provide a custom function (dir: string) => boolean to extend this behavior.