GithubHelp home page GithubHelp logo

vite-tsconfig-paths's Introduction

👋 Do you like Postgres 🐘? I'm making a 100% type-safe query builder (not an ORM), and I want your help fleshing it out.
Btw, it generates the types and client from your database schema, so it's never out-of-date and you have access to every native Postgres function!
I want to add a powerful plugin system soon, and eventually all functionality will be pluggable.

Learn more


vite-tsconfig-paths

npm codecov Code style: Prettier Donate

Give vite the ability to resolve imports using TypeScript's path mapping.

Usage

  1. Install as dev dependency

  2. Inject vite-tsconfig-paths using the vite.config.ts module

    import { defineConfig } from 'vite'
    import tsconfigPaths from 'vite-tsconfig-paths'
    
    export default defineConfig({
      plugins: [tsconfigPaths()],
    })

Note: You need to restart Vite when you update your paths mappings.

Options

  • root: string
    The directory to search for tsconfig.json files.

    The default value of this option depends on whether projects is defined. If it is, then the Vite project root is used. Otherwise, Vite's searchForWorkspaceRoot function is used.

  • projects: string[]
    If you have an esoteric setup, you might need this option to specify where your tsconfig files are located. The paths within are relative to the root option.

    If defined, the root directory won't be searched for tsconfig files. You should always try using just the root option first, because this option is more brittle.

  • loose: boolean
    Disable strictness that limits path resolution to TypeScript and JavaScript importers.

    Useful if you want imports in Vue templates to be resolved, but don't want to use allowJs in your tsconfig, for example.

    In other words, when loose: true is used, any file that gets transpiled into JavaScript will have its imports resolved by this plugin.

  • parseNative: boolean
    Enable use of the tsconfck.parseNative function, which delegates the loading of tsconfig files to the TypeScript compiler. You'll probably never need this, but I added it just in case.

    ⚠️ This option can slow down Vite's startup time by as much as 600ms, due to the size of the TypeScript compiler. Only use it when necessary.

  • ignoreConfigErrors: boolean
    When true, parsing errors encountered while loading tsconfig files will be ignored. This is useful if you have a monorepo with multiple tsconfig files, and you don't want to see errors for the ones that aren't relevant to the current project.

 

allowJs

If your tsconfig file has "allowJs": true in it, path resolution will be expanded beyond TypeScript importers. The following extensions will have their imports resolved by this plugin: .vue, .svelte, .mdx, .mjs, .js, .jsx

 

baseUrl

If the baseUrl is defined, it gets prepended to all bare imports, and its resolution will take precedence over node_modules. This is also how TypeScript does it.

Say the baseUrl is ../root and you import react. This plugin will use ../root/react if it exists. If not found, then react is resolved normally. The baseUrl is relative to the project root (where tsconfig.json lives).

 

include/exclude

The include and exclude tsconfig options are respected.

Internally, globrex is used for glob matching.

 

Troubleshooting

The DEBUG environment variable can be used to figure out why this plugin isn't working as you may have expected.

DEBUG=vite-tsconfig-paths yarn vite

Also, check out the Troubleshooting wiki page for more guidance.

vite-tsconfig-paths's People

Contributors

aleclarson avatar christopherschroer avatar daihere1993 avatar difuks avatar fwouts avatar gunters63 avatar haikyuu avatar igordreher avatar jamesknelson avatar jeremy-coleman avatar jgoux avatar josh-hemphill avatar joshwooding avatar lanthaler avatar monkatraz avatar naranjamecanica avatar pcattori avatar thebuilder avatar trixterthetux avatar wadefletch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

vite-tsconfig-paths's Issues

Doesn't work with custom server

I'm running Vite dev with a custom Express server, and after upgrading vite-tsconfig-paths from version 2.5.1 it breaks.
Seems to work if just running vite dev.

./node_modules/vite-tsconfig-paths/dist/index.js:124
                                    done(viteResolve(path, importer));
                                         ^

TypeError: viteResolve is not a function
    at ./node_modules/vite-tsconfig-paths/dist/index.js:124:42
    at ./node_modules/tsconfig-paths/lib/match-path-async.js:72:24
    at ./node_modules/tsconfig-paths/lib/filesystem.js:46:9
    at FSReqCallback.oncomplete (fs.js:184:5)

viteResolve is set in buildStart, but this function is never called.
https://github.com/aleclarson/vite-tsconfig-paths/blob/master/src/index.ts#L21

It breaks the moment I try to load a module using vite.ssrLoadModule. I've tried trim the server.mjs file down to the essentials:

server.mjs

import { createServer as createViteServer } from "vite";
import express from "express";

export async function createServer(root = process.cwd()) {
  const app = express();

  const vite = await createViteServer({
    root,
    logLevel: "info",
    server: {
      middlewareMode: true
    }
  });

  app.use(vite.middlewares);

  app.use("*", async (req, res, next) => {
    await vite.ssrLoadModule("/src/entry-server.ts");

    res.status(200).end("output");
  });

  return { app, vite };
}
async function init() {
  const { app } = await createServer();

  app.listen(3000, () => {});
}

init();

import "~/lib"; doesn't get processed

Hope I've got the right repo to report this, but I'm seeing the following issue:

// lib.ts
export const nothing = null;

// app.ts :: works
import { nothing } from '~/lib';

// app.ts :: fails
import '~/lib';

As you can see, just importing any old thing will trigger the path-transforming logic.

Doesn't work with Svelte

This plugin doesn't seem to work with Svelte files.

I can see in this issue that the goal would be to only apply this script to .vue modules :

@scambier See #4. The path mapping should only apply to lang="ts" scripts in .vue modules, but it's not implemented yet.

With Vite 2 becoming framework agnostic, I was wondering if this stance will still be kept? Or am I missing something in my config? I'd like to use this for automatic path mapping, it's really useful!

Thanks in advance!

Suggestion: Less magic project lookup to increase the developer experience

First, thanks for a great plugin. 👏

Here comes a suggestion. :)

Context

Background: When I recently moved my index.html file to a subfolder (i.e. changing the root folder configuration), I wasted some time with a failing build due to Vite being unable to resolve path alias... This was due to the rather magical lookup behaviour provided by vite-tsconfig-paths.

As documented in the README, the plugin currently automatically finds all tsconfig files in the same folder as the vite root. It means that it usually works for simple setup, but can cause confusing and rather error-prone scenarios as shown above. Another surprise was that it located multiple tsconfig files (some that we use for other parts of the codebase that isn't relevant for Vite). And the plugin silently failed to resolve.

Pain points:

  • automatically finding tsconfig files can lead to misconfiguration (e.g. in case with multiple tsconfig files)
  • silently failing doesn't provide a great user experience

Workaround

Being explicit about the tsconfig projects seems like the safest way to use the plugin:

tsconfigPaths({projects: [path.resolve(__dirname, 'tsconfig.json')]})

Suggestion

This would be breaking change, but I believe a better and safer API would be to always let the user specify the tsconfig projects and never automatically resolve them. This basically means getting rid of root and extensions, and a user would need to specify the projects when using the plugin (as mentioned in the workaround).

And if the file resolution fails then the plugin should crash.

If we want a no config behaviour (i.e. tsconfigPaths()) then I suggest defaulting to a tsconfig.json file – but fail if the file cannot be resolved.

Paths never get remapped on Windows

Tried using this module on Linux, and it seems to do a great job.

Though on a Windows environment it seems that the resolve for root here breaks the local descendant output due to generating the root in a different format. Originally, the root passed to configResolved is in the format of /Users/..., but the resolve() changes it to the format of C:\Users\....

The resolveId's importer variable follows the root variable's path scheme, so the isLocalDescendant function will never be able to correctly validate that the path starts with root (as it compares format of /Users/... to C:\Users\...). It also additionally uses sep after the resolve, which seems to be always / for importer's paths (instead of sep's value \ on Windows) from my testing.

Changing the mentioned line to root = (opts.root || root) + '/'; seems to fix the issue on both OSes, though I don't know if this is a good fix due to opts.root being configurable by the user and it could follow the C:\Users\... format too due to usage of e.g. process.cwd() or path.join().

Doesn't work with scss file

config:

import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';

// https://vitejs.dev/config/
export default defineConfig(configEnv => ({
  plugins: [
    tsconfigPaths({ extensions: ['ts', 'tsx', 'scss', 'css'] }),
    ...
  ],
  ...
}));

tsconfig.json:

{
  "compilerOptions": {
    "target": "ESNext",
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "types": ["vite/client"],
    "allowJs": false,
    "skipLibCheck": false,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "useDefineForClassFields": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": "src"
  },
  "include": ["./src"]
}

I set baseUrl to src dir, and import some scss by @use 'style/color'(there is a file in /src/style/color.scss )

Everything works fine when I manually configure the alias, but when I use vite-tsconfig-paths it throws an error:

image

2:08:14 PM [vite] Internal server error: Can't find stylesheet to import.
  ╷
1 │ @use 'style/color';
  │ ^^^^^^^^^^^^^^^^^^
  ╵
  src/style/global.scss 1:1  root stylesheet
  Plugin: vite:css
  File: /Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/src/style/global.scss
  Error: Can't find stylesheet to import.
    ╷
  1 │ @use 'style/color';
    │ ^^^^^^^^^^^^^^^^^^
    ╵
    src/style/global.scss 1:1  root stylesheet
      at Object._newRenderError (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:13174:19)
      at Object._wrapException (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:13000:16)
      at _render_closure1.call$2 (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:81147:21)
      at _RootZone.runBinary$3$3 (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:27268:18)
      at _FutureListener.handleError$1 (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:25818:19)
      at _Future__propagateToListeners_handleError.call$0 (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:26116:49)
      at Object._Future__propagateToListeners (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:4539:77)
      at _Future._completeError$2 (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:25948:9)
      at _AsyncAwaitCompleter.completeError$2 (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:25602:12)
      at Object._asyncRethrow (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:4338:17)
2:08:14 PM [vite] Internal server error: Can't find stylesheet to import.
  ╷
1 │ @use 'style/color';
  │ ^^^^^^^^^^^^^^^^^^
  ╵
  src/style/override/formElementCommon.scss 1:1  @use
  src/style/override/index.scss 1:1              root stylesheet
  Plugin: vite:css
  File: /Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/src/style/override/formElementCommon.scss
  Error: Can't find stylesheet to import.
    ╷
  1 │ @use 'style/color';
    │ ^^^^^^^^^^^^^^^^^^
    ╵
    src/style/override/formElementCommon.scss 1:1  @use
    src/style/override/index.scss 1:1              root stylesheet
      at Object._newRenderError (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:13174:19)
      at Object._wrapException (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:13000:16)
      at _render_closure1.call$2 (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:81147:21)
      at _RootZone.runBinary$3$3 (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:27268:18)
      at _FutureListener.handleError$1 (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:25818:19)
      at _Future__propagateToListeners_handleError.call$0 (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:26116:49)
      at Object._Future__propagateToListeners (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:4539:77)
      at _Future._completeError$2 (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:25948:9)
      at _AsyncAwaitCompleter.completeError$2 (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:25602:12)
      at Object._asyncRethrow (/Users/vimcaw/ProjectsAtWork/deep-loving-cloud-admin/node_modules/sass/sass.dart.js:4338:17)


Cannot resolve alias in template when using Pug

When I start to use pug, this plugin throw a resolve error.

  1. app pug support
npm install pug --save-dev
#or
yarn add -D pug
  1. App.vue here:
<template lang="pug">
img(alt="Vue logo" src="@/assets/logo.png")
</template>
  1. tsconfig.json here:
{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": ["esnext", "dom"],
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "components/*": ["src/components/*"]
    }
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
  1. vite.config.ts here:
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  base: "/CheckingBoard/",
  server: {
    open: true,
  },
  plugins: [vue(), tsconfigPaths({ loose: true })],
});
  1. error here:
[vite] Internal server error: Failed to resolve import "@/assets/logo.png" from "src\App.vue?vue&type=template&lang.js". Does the file exist?
  Plugin: vite:import-analysis
  File: S:/workplace/CheckingBoard/src/App.vue?vue&type=template&lang.js
  1  |  import { createElementVNode as _createElementVNode, toDisplayString as _toDisplayString, createVNode as _createVNode, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock } from "vue"       
  2  |  import _imports_0 from '@/assets/logo.png'
     |                          ^
  3  |  
  4  |  
      at formatError (S:\workplace\CheckingBoard\node_modules\vite\dist\node\chunks\dep-36bf480c.js:50163:46)
      at TransformContext.error (S:\workplace\CheckingBoard\node_modules\vite\dist\node\chunks\dep-36bf480c.js:50159:19)
      at normalizeUrl (S:\workplace\CheckingBoard\node_modules\vite\dist\node\chunks\dep-36bf480c.js:75881:26)
      at processTicksAndRejections (internal/process/task_queues.js:93:5)
      at async TransformContext.transform (S:\workplace\CheckingBoard\node_modules\vite\dist\node\chunks\dep-36bf480c.js:76016:57)
      at async Object.transform (S:\workplace\CheckingBoard\node_modules\vite\dist\node\chunks\dep-36bf480c.js:50373:30)
      at async transformRequest (S:\workplace\CheckingBoard\node_modules\vite\dist\node\chunks\dep-36bf480c.js:65414:29)
      at async viteTransformMiddleware (S:\workplace\CheckingBoard\node_modules\vite\dist\node\chunks\dep-36bf480c.js:65542:32)

I'm not sure if it is possible to fix easily.

ref: https://github.com/aleclarson/vite-tsconfig-paths/blob/master/src/index.ts#L113

I found that if using HTML, the importer here is:

S:/workplace/CheckingBoard/src/App.vue

When set lang="pug", the importer will change to:

S:/workplace/CheckingBoard/src/App.vue?vue&type=template&lang.js

To temporary fix the problem, update the include in tsconfig.json:

-"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
+"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue", "src/**/*.js"]

type declaration missing in package.json exports

I am currently converting my Typescript project to fully ESM ("type": "module" in package.json and
"moduleResolution": "Node16" in tsconfig).

The import statement:

import tsconfigPaths from 'vite-tsconfig-paths';

now gives me the following error message:

Could not find a declaration file for module 'vite-tsconfig-paths'. 'D:/proj/AtlasCopco/EnsoUi/node_modules/.pnpm/[email protected][email protected]/node_modules/vite-tsconfig-paths/dist/index.mjs' implicitly has an 'any' type.

I looked in the package.json of vite-tsconfig-paths and it seems there is a type declaration missing for the exports:

  "exports": {
    "import": "./dist/index.mjs",
    "require": "./dist/index.js"
  },

If I manually change this to:

  "exports": {
    "types": "./dist/index.d.ts",
    "import": "./dist/index.mjs",
    "require": "./dist/index.js"
  },

the error goes away.

Recrawl-sync error on local build error with docker

#13 0.783 > tsc && vite build
#13 0.783
#13 17.00 error during build:
#13 17.00 Error: ELOOP: too many symbolic links encountered, stat '//proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/proc/1/cwd/dev/fd/0'
#13 17.00     at Object.statSync (node:fs:1538:3)
#13 17.00     at Object.stat (/node_modules/recrawl-sync/lib/fs.js:10:22)
#13 17.00     at crawl (/node_modules/recrawl-sync/lib/recrawl.js:55:31)
#13 17.00     at crawl (/node_modules/recrawl-sync/lib/recrawl.js:70:29)
#13 17.00     at crawl (/node_modules/recrawl-sync/lib/recrawl.js:70:29)
#13 17.00     at crawl (/node_modules/recrawl-sync/lib/recrawl.js:70:29)
#13 17.00     at crawl (/node_modules/recrawl-sync/lib/recrawl.js:70:29)
#13 17.00     at crawl (/node_modules/recrawl-sync/lib/recrawl.js:70:29)
#13 17.00     at crawl (/node_modules/recrawl-sync/lib/recrawl.js:70:29)
#13 17.00     at crawl (/node_modules/recrawl-sync/lib/recrawl.js:70:29)
#13 ERROR: executor failed running [/bin/sh -c npm run build]: exit code: 1
------
 > [build-stage 5/5] RUN npm run build:
------
------
executor failed running [/bin/sh -c npm run build]: exit code: 1

Im getting this when building locally with docker

Failed to resolve import in a vue-ts project

I failed to add vite-tsconfig-paths to a project that also has storybook, even if I configured the right file.

After that, I simplified the process and added vite-tsconfig-paths to the actual vite configuration. Still did not work.

Now I tried a new vue-ts repo created with vite, and added vite-tsconfig-paths, problem still persists 🤔

I tried to configure global aliases like @/* or ~/*
Even tried with some namespace like @app/* all of them fail to resolve import. 🤔

Here is the commit in which I added vite-tsconfig-paths

npm run dev

In the terminal console, result is pretty much the same 👀

image

Reproduction repo: https://github.com/iamandrewluca/issue-vite-tsconfig-paths

❯ node -v
v16.15.1

❯ npm -v
8.13.2

❯ npx -v
8.13.2

❯ uname -sm
Darwin arm64

❯ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version
Google Chrome 103.0.5060.53

As a temporary workaround, I added the alias manually to vite configuration, and adjusted tsconfig.json paths just for IDE completion.

vite.config.ts
import * as path from 'node:path';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
	plugins: [vue()],
	resolve: {
		alias: { '~': path.resolve(__dirname, 'src') },
	},
});
.storybook/main.js
const path = require('node:path');
const { mergeConfig } = require('vite');

module.exports = {
	stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
	addons: [
		'@storybook/addon-links',
		'@storybook/addon-essentials',
		'@storybook/addon-interactions',
	],
	framework: '@storybook/vue3',
	core: {
		builder: '@storybook/builder-vite',
	},
	features: {
		storyStoreV7: true,
	},
	viteFinal: (config) =>
		mergeConfig(config, {
			resolve: {
				alias: { '~': path.resolve(__dirname, '../src') },
			},
		}),
};

cannot find `"@/containers-legacy/workorder/actions/kpiOrder/"`

env:

➜  honor git:(master) ✗ yarn vite --force
error when starting dev server:
Error: The following dependencies are imported but could not be resolved:

  @/containers-legacy/workorder/actions/kpiOrder/ (imported by /Users/weiran/repo/dian/honor/src/containers-legacy/workorder/pages/kpiOrder/index.jsx)

There is something like import actions from '@/containers-legacy/workorder/actions/kpiOrder/' in our codebase. it's working after removing the last /.

Cannot resolve paths of submodule.

When I created git submodule, I tried to use this plugin to correctly resolve paths of the submodule. But unfortunately I am getting this error:
image

All the paths, but the submodule paths, seems to be resolving correctly.

My vite config (main project):

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vuetify from '@vuetify/vite-plugin'
import { vueAndTsChecker } from 'vite-plugin-typescript-vue-checker';
import tsconfigPaths from 'vite-tsconfig-paths'

// eslint-disable-next-line
export default defineConfig({
  plugins: [
    vue(),
    // https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin
    vuetify({ autoImport: true }),
    vueAndTsChecker(),
    tsconfigPaths({
      projects: [
        './tsconfig.json',
        './submodule/lil-mole/tsconfig.json'
      ]
    }),
  ],
})

ts config (main project):

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": ["cypress", "node"],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "cypress/**/*.ts",
    "cypress/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ],
  "rootDirs": ["src/", "submodule/lil-mole/"]
}
 

ts config (submodule):

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": ["cypress"],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "cypress/**/*.ts",
    "cypress/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

Doesn't work with Vite 2

The plugin doesn't work with Vite 2:

failed to load config from /xxx/vite.config.ts
error when starting dev server:
Error: Cannot find module 'vite/dist/node/resolver'
Require stack:
- /xxx/node_modules/vite-tsconfig-paths/dist/index.js
- /xxx/vite.config.ts

It also seems that resolvers is not more a valid property at vite.UserConfig.

Support Vite resource import

vite can import file use ?raw or ?url and so on, when use it, plugin can't resolveId
should substring it:

 if (/.+\?.*$/.test(id)) {
     id = id.split('?')[0]
 }

Support checkJs

Would also be nice if the path mappings could optionally be applied to *js files as well. Should maybe even be enabled by default when checkJs is enabled in the tsconfig.json.

Originally posted by @DreierF in #4 (comment)

ESModules: tsconfigPaths is not a function; no default export

In an ESModule project, the default export is { default: [Function (anonymous)] } which also breaks type information in ESM Typescript projects.

I've had to do this to work around it:

import _tsconfigPaths from 'vite-tsconfig-paths';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
const tsconfigPaths: typeof _tsconfigPaths = _tsconfigPaths.default;

Perhaps the easiest solution would be to create two dist bundles, one classic Node and one ESM. In trying to make my own vite plugins and looking at the others out there, creating two bundles seems to be pretty ubiquitous.

Reproduction: https://github.com/josh-hemphill/vite-tsconfig-paths/tree/esm-errored

Feature request: Allow customizing the files path mapping applies in

Currently, you're not able to configure in which files the path mapping works due to the check here. It'd be nice to allow it to be configured so that you can allow e.g. vue files to import other files using the path mappings (or possibly use tsconfig's include types to automatically detect this?).

[vite:css] Failed to find '@/norm.css'

[vite:css] Failed to find '@/norm.css'
  in [
    /Users/weiran/repo/dian/vite-tsconfig-paths/demo/src
  ]
file: /Users/weiran/repo/dian/vite-tsconfig-paths/demo/src/styles.css
error during build:
Error: Failed to find '@/norm.css'

I've made a repro: #42

vite.defineConfig is not a function

TypeError: vite.defineConfig is not a function
viite:vite/2.4.4 win32-x64 node-v14.15.4
vue: "^3.0.4"
node:v14.15.4
npm:6.14.10

import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'

export default defineConfig({
  plugins: [tsconfigPaths()],
})

Feature request: possibility to configure the root tsconfig.json

Hey,

thanks for the project. We use it for our Vite Nx integration. Right now we, unfortunately, have a problem already mentioned here: #47

Could you make the root tsconfig.json filename be configurable? In an Nx monorepo the root tsconfig is by default 'tsconfig.base.json' and renaming it would break compatibility.

Great thanks and best regards

Unable to resolve dependency of dependency

Here's my setup. I have a monorepo. In that monorepo, I have @taxbit/demos which uses @taxbit/browser which uses @taxbit/rest (all three are on the same repo). When I run vite on @taxbit/demos, I get the following error:

✘ [ERROR] [plugin vite:dep-scan] Failed to resolve entry for package "@taxbit/rest". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package "@taxbit/rest". The package may have incorrect main/module/exports specified in its package.json.

    ../../node_modules/vite/dist/node/chunks/dep-8f5c9290.js:40945:10:
      40945 │     throw new Error(`Failed to resolve entry for package "${id}". ` +
            ╵           ^

    at packageEntryFailure (/Users/aaron/dev/taxbit-browser/node_modules/vite/dist/node/chunks/dep-8f5c9290.js:40945:11)
    at resolvePackageEntry (/Users/aaron/dev/taxbit-browser/node_modules/vite/dist/node/chunks/dep-8f5c9290.js:40941:9)
    at tryNodeResolve (/Users/aaron/dev/taxbit-browser/node_modules/vite/dist/node/chunks/dep-8f5c9290.js:40748:20)
    at Context.resolveId (/Users/aaron/dev/taxbit-browser/node_modules/vite/dist/node/chunks/dep-8f5c9290.js:40556:28)
    at Object.resolveId (/Users/aaron/dev/taxbit-browser/node_modules/vite/dist/node/chunks/dep-8f5c9290.js:39229:55)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async resolve (/Users/aaron/dev/taxbit-browser/node_modules/vite/dist/node/chunks/dep-8f5c9290.js:39441:26)
    at async /Users/aaron/dev/taxbit-browser/node_modules/vite/dist/node/chunks/dep-8f5c9290.js:39601:34
    at async callback (/Users/aaron/dev/taxbit-browser/node_modules/esbuild/lib/main.js:929:28)
    at async handleRequest (/Users/aaron/dev/taxbit-browser/node_modules/esbuild/lib/main.js:709:30)

  This error came from the "onResolve" callback registered here:

    ../../node_modules/vite/dist/node/chunks/dep-8f5c9290.js:39591:18:
      39591 │             build.onResolve({
            ╵                   ~~~~~~~~~

    at setup (/Users/aaron/dev/taxbit-browser/node_modules/vite/dist/node/chunks/dep-8f5c9290.js:39591:19)
    at handlePlugins (/Users/aaron/dev/taxbit-browser/node_modules/esbuild/lib/main.js:851:23)
    at Object.buildOrServe (/Users/aaron/dev/taxbit-browser/node_modules/esbuild/lib/main.js:1145:7)
    at /Users/aaron/dev/taxbit-browser/node_modules/esbuild/lib/main.js:2087:17
    at new Promise (<anonymous>)
    at Object.build (/Users/aaron/dev/taxbit-browser/node_modules/esbuild/lib/main.js:2086:14)
    at Object.build (/Users/aaron/dev/taxbit-browser/node_modules/esbuild/lib/main.js:1935:51)
    at /Users/aaron/dev/taxbit-browser/node_modules/vite/dist/node/chunks/dep-8f5c9290.js:39389:54
    at Array.map (<anonymous>)

  The plugin "vite:dep-scan" was triggered by this import

    ../sdk/src/TaxBit.ts:9:23:
      9 │ import TaxBitRest from "@taxbit/rest";
        ╵                        ~~~~~~~~~~~~~~

Build failed with 1 error:
../../node_modules/vite/dist/node/chunks/dep-8f5c9290.js:40945:10: ERROR: [plugin: vite:dep-scan] Failed to resolve entry for package "@taxbit/rest". The package may have incorrect main/module/exports specified in its package.json: Failed to resolve entry for package "@taxbit/rest". The package may have incorrect main/module/exports specified in its package.json.

Here are my files:

@taxbit/demos tsconfig.json:

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "incremental": true,
    "jsx": "react-jsx",
    "baseUrl": "./",
    "paths": {
      "~/*": ["./src/*"],
      "@taxbit/browser": ["../sdk/src/main.ts"],
      "@taxbit/rest": ["../rest/src/main.ts"]
    }
  },
  "include": ["src"]
}

@taxbit/demos vite.config.json

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [tsconfigPaths(), react()],
});

@taxbit/browser tsconfig.json:

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ESNext", "DOM"],
    "moduleResolution": "Node",
    "strict": true,
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noUncheckedIndexedAccess": true,
    "declaration": true,
    "emitDeclarationOnly": true,
    "baseUrl": "./",
    "rootDir": "./src",
    "outDir": "./dist",
    "paths": {
      "@taxbit/rest": ["../rest/src/main.ts"]
    },
    "composite": true
  },
  "include": ["./src"],
  "references": [
    {
      "path": "../rest"
    }
  ]
}

@taxbit/browser vite.config.json:

import { defineConfig } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [tsconfigPaths()],
  build: {
    lib: {
      entry: "./src/main.ts",
      name: "taxbit",
      fileName: (format) => `taxbit.${format}.js`,
    },
  },
});

@taxbit/rest tsconfig.json:

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ESNext", "DOM"],
    "moduleResolution": "Node",
    "strict": true,
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noUncheckedIndexedAccess": true,
    "declaration": true,
    "rootDir": "./src",
    "outDir": "./dist",
    "composite": true
  },
  "include": ["./src"]
}

@taxbit/rest vite.config.json:

import { defineConfig } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [tsconfigPaths()], // probably not necessary
  build: {
    lib: {
      entry: "./src/main.ts",
      name: "taxbit",
      fileName: (format) => `taxbit.${format}.js`,
    },
  },
});

When I don't use vite-tsconfig-paths, but instead manually configure resolve.alias within vite.config.json, I don't get an error. Here's what my vite.config.json files look like when manually configured:

@taxbit/demos vite.config.json:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import * as path from "path";

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      "~": path.resolve(__dirname, "src"),
      "@taxbit/browser": path.resolve(__dirname, "../sdk/src/main.ts"),
      "@taxbit/rest": path.resolve(__dirname, "../rest/src/main.ts"),
    },
  },
});

@taxbit/browser vite.config.json

import { defineConfig } from "vite";
import * as path from "path";

export default defineConfig({
  resolve: {
    alias: {
      "@taxbit/rest": path.resolve(__dirname, "../rest/src/main.ts"),
    },
  },
  build: {
    lib: {
      entry: "./src/main.ts",
      name: "taxbit",
      fileName: (format) => `taxbit.${format}.js`,
    },
  },
});

@taxbit/rest vite.config.json

import { defineConfig } from "vite";

export default defineConfig({
  build: {
    lib: {
      entry: "./src/main.ts",
      name: "taxbit",
      fileName: (format) => `taxbit.${format}.js`,
    },
  },
});

I'm still pretty new at configuring TS and Vite, so it's very possible I'm misunderstanding something. Thanks for the help!

Regression 3.3.2 -> 3.3.3

Updating from 3.3.2 to 3.3.3 breaks dev server and build with the following error:

error during build:
Error: ENOENT: no such file or directory, stat 'D:\proj\AtlasCopco\EnsoUi/D:/proj/AtlasCopco/EnsoUi/tsconfig.json'
    at Object.statSync (fs.js:1086:3)
    at resolveConfigPath (D:\proj\AtlasCopco\EnsoUi\node_modules\.pnpm\[email protected]\node_modules\tsconfig-paths\lib\tsconfig-loader.js:48:12)
    at loadSyncDefault (D:\proj\AtlasCopco\EnsoUi\node_modules\.pnpm\[email protected]\node_modules\tsconfig-paths\lib\tsconfig-loader.js:26:22)

I am using Windows and Node 14 LTS.
I guess some recent changes broke path handling on Windows.

change checkJs to allowJs.

the typescript setting allowJs is more appropriate for the use case. If a user wants to include and resolve javascript , that doesnt mean they also want typescript to check it. I'm sure checkjs causes a ton of headaches in users' IDE too.

open PR here #16

missing baseUrl

I am using tsconfig path to import a file outside of project root, like:

"paths": {
      "shared/*": [
        "../shared/*"
      ],
    }

this is working on other webpack/esbuild projects, but not with this plugin. I used debug mode and logged the following error:

vite-tsconfig-paths crawling "/Users/admin/.../my-project" +0ms
vite-tsconfig-paths options: {
  projects: [ '/Users/admin/.../my-project/tsconfig.json' ],
  extensions: [ '.ts', '.tsx', '.js', '.jsx', '.mjs' ]
} +4ms
vite-tsconfig-paths [!] missing baseUrl: "/Users/admin/.../my-project/tsconfig.json" +4ms

and vite throws the error as if the plugin is not used

Error: The following dependencies are imported but could not be resolved:

Unable to use this plugin from custom extensions (like .vue)

Seems that it is impossible to allow inclusions from specific file extensions (e.g. .vue) with the tsconfig's included parameter due to the following line here as it converts any custom extension glob into a one that will always match directories only, e.g. ./src/**/*.vue will convert to ./src/**/*.vue/**

Version: 3.3.10 (previously tested 3.2.1 where it worked as intended)
The plugin is initialized like this:

tsconfigPaths({
    extensions: ['.ts', '.tsx', '.js', '.jsx', '.json', '.vue'],
})

Recursively Resolving Paths Outside Tsconfig Includes Array

Thanks for creating such a useful package @aleclarson! During development, I've noticed what I think is a small bug affecting module resolution.

I've prepared a minimal reproduction here:
https://github.com/auzmartist/vite-tsconfig-paths-recursive-resolution

Some analysis of the vite debug output...

Problem

Using vite-tsconfig-paths, modules placed outside the includes array are normally resolved. However, this only extends to first order dependencies - dependencies referenced directly from project source.

However, if these first order dependencies, depend on other pathed modules which are similarly outside the tsconfig include array, errors are produced during module resolution.

Example Annotated Output

DEBUG=vite-tsconfig-paths vite

Here we crawl for a tsconfig.json.
Notably, two paths @moduleA and @moduleB are configured which point to TS modules in ./modules.

> DEBUG=vite-tsconfig-paths vite

  vite-tsconfig-paths crawling "/mnt/f/dev/forked/vite-tsconfig-paths-example" +0ms
  vite-tsconfig-paths options: {
  projects: [ '/mnt/f/dev/forked/vite-tsconfig-paths-example/tsconfig.json' ],
  extensions: [ '.ts', '.tsx', '.js', '.jsx', '.mjs' ]
} +9ms
  vite-tsconfig-paths config loaded: {
  configPath: '/mnt/f/dev/forked/vite-tsconfig-paths-example/tsconfig.json',
  include: [ 'src/**/*.ts' ],
  exclude: undefined,
  allowJs: undefined,
  baseUrl: undefined,
  paths: {
    '@moduleA': [ './modules/moduleA' ],
    '@moduleB': [ './modules/moduleB' ]
  },
  outDir: undefined
} +4ms

Here, we see that the tsconfig only includes TS modules within ./src.

  vite-tsconfig-paths compiled globs: {
  included: [ /^\.\/src\/((?:[^/]*(?:\/|$))*)([^/]*)\.ts$/ ],
  excluded: [
    /^\.\/node_modules\/((?:[^/]*(?:\/|$))*)$/,
    /^\.\/bower_components\/((?:[^/]*(?:\/|$))*)$/,
    /^\.\/jspm_packages\/((?:[^/]*(?:\/|$))*)$/
  ]
} +0ms

Here we start up the dev server and begin resolving modules.

  vite v2.9.9 dev server running at:

  > Local: http://localhost:3000/
  > Network: use `--host` to expose

  ready in 575ms.

Here we resolve @moduleA.

  vite-tsconfig-paths resolved: {
  id: '@moduleA',
  importer: '/mnt/f/dev/forked/vite-tsconfig-paths-example/src/index.ts',
  resolvedId: '/mnt/f/dev/forked/vite-tsconfig-paths-example/modules/moduleA.ts',
  configPath: '/mnt/f/dev/forked/vite-tsconfig-paths-example/tsconfig.json'
} +125ms

Here we resolve @moduleb.

  vite-tsconfig-paths resolved: {
  id: '@moduleB',
  importer: '/mnt/f/dev/forked/vite-tsconfig-paths-example/src/index.ts',
  resolvedId: '/mnt/f/dev/forked/vite-tsconfig-paths-example/modules/moduleB.ts',
  configPath: '/mnt/f/dev/forked/vite-tsconfig-paths-example/tsconfig.json'
} +8ms

Here we see that we cannot resolve @moduleA depended on by @moduleb:

The following dependencies are imported but could not be resolved:

  @moduleA (imported by /mnt/f/dev/forked/vite-tsconfig-paths-example/modules/moduleB.ts)

Are they installed?
Failed to resolve import "@moduleA" from "modules/moduleB.ts". Does the file exist?
5:14:16 PM [vite] Internal server error: Failed to resolve import "@moduleA" from "modules/moduleB.ts". Does the file exist?
  Plugin: vite:import-analysis
  File: /mnt/f/dev/forked/vite-tsconfig-paths-example/modules/moduleB.ts
  1  |  import { A } from "@moduleA";
     |                     ^
  2  |  export function B() {
  3  |    return `MODULE B: ${A}`;
      at formatError (/mnt/f/dev/forked/vite-tsconfig-paths-example/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:38663:46)
      at TransformContext.error (/mnt/f/dev/forked/vite-tsconfig-paths-example/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:38659:19)
      at normalizeUrl (/mnt/f/dev/forked/vite-tsconfig-paths-example/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:56830:26)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)
      at async TransformContext.transform (/mnt/f/dev/forked/vite-tsconfig-paths-example/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:56979:57)
      at async Object.transform (/mnt/f/dev/forked/vite-tsconfig-paths-example/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:38900:30)
      at async doTransform (/mnt/f/dev/forked/vite-tsconfig-paths-example/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:55857:29)

I am not sure if this is the intended behavior of the plugin but it certainly seems unexpected that the tsconfig paths would only apply to dependencies imported from modules within the include array. Perhaps this could be expanded to apply to all modules by default and the current "strict" implementation offered as a configuration option? What do you think?

Cannot find module tsconfig-paths\lib\tsconfig-loader in ESM mode

I want to switch to ESM mode ("type": "module").
vite-tsconfig-paths gives me above error.
It seems ESM should be supported because I can see

  "exports": {
    "import": "./dist/index.mjs",
    "require": "./dist/index.js"
  },

in the package.json of vite-tsconfig-paths so it should be a hybrid module.

When I look into dist/index.mjs there is the following include:

import {
  loadTsconfig,
  walkForTsConfig
} from "tsconfig-paths/lib/tsconfig-loader";

which fails

Transitive dependencies are not resolved

I have the same problem described in issue #12 which is closed.
An example repository can be found here: https://github.com/realityfilter/bug-transitive-deps

the structure is
app: uses liba
liba: uses libb
libb

Just run nx serve app
Resulting in the error:

  The following dependencies are imported but could not be resolved:
  @trans-dep/libb (imported by /Users/vb/Desktop/nx-vite-dep/trans-dep/packages/liba/src/lib/liba.ts)

I tried the workaround described in issue #12:

tsconfigPaths({
  root: '../..',
})

with no success.

TSConfig imports do not work in WebWorkers

I'm trying to use WebWorkers with this plugin using the built in tooling provided by Vite.

Unfortunately I get issues when the worker is invoked, it's unable to resolve any imports using the tsconfig file and will only work if I continue to use relative imports.

I've also tested this using the resolve alias feature in the Vite config and it worked as expected, so the issue is isolated to the plugin itself.

I've setup a stackblitz where you can see the issue directly, if there's any more info you need from me just let me know.

https://stackblitz.com/edit/vite-tsconfigpaths-webworker

ESM import `~/lib/util.js` doesn't work.

With the introduction of ES Modules in TypeScript 4.7, TypeScript needs every import to have an extension. For example, if I have a file util.ts, I would need to import it as ./utils.js (so that when transpiles to plain JavaScript, the import works as expected).

The addition of a .js to an aliased path by the plugin breaks the resolution. For example:

import "~/lib/util" // TS Error: module not found
import "../util.js" // ok
import "~/lib/util.js" // No TS Error, but Rollup throws "Rollup failed to resolve import"

Support jsconfig.json?

Hi, would it be possible to also support jsconfig.json to make baseUrl work for non-ts projects too?

Can't handle directories outsite of `root`

- myProject
  - src
    - driver
      - view
        - pages
          - index.vue
        - index.html
    - domain
      - service
        - service1.ts
  - tsconfig.json
  - vite.config.ts

my project directory structure is like above. Here is my vite.config.ts:

export default defineConfig({
  root: './src/driver/view',
  plugins: [
    tsconfigPaths({ root: process.cwd() }),
    vue(),
  ],
});

and compilerOptions.paths in tsconfig.json is like this:

{
      "domain/*": ["./src/domain/*"],
      "driver/*": ["./src/driver/*"]
}

in index.vueimport domain/service/service1 not work, since browser report

Uncaught SyntaxError: The requested module '/@id/__vite-browser-external:domain/service/service1.ts' does not provide an export named 'service1'

in console.

It seems that vite thought domain/service/service1 is an external module. I inserted an console.log(id) in node_modules/vite-tsconfig-paths/dist/index.js and DEBUG=vite-tsconfig-paths yarn vite, this is output:

driver/http
  vite-tsconfig-paths resolved: {
  id: 'driver/http',
  importer: '/Users/chenyulu/code/mall-webapp/src/driver/view/main.ts',
  resolvedId: '/Users/chenyulu/code/mall-webapp/src/driver/http/index.ts',
  configPath: '/Users/chenyulu/code/mall-webapp/tsconfig.json'
} +651ms
driver/env
  vite-tsconfig-paths resolved: {
  id: 'driver/env',
  importer: '/Users/chenyulu/code/mall-webapp/src/driver/view/main.ts',
  resolvedId: '/Users/chenyulu/code/mall-webapp/src/driver/env/index.ts',
  configPath: '/Users/chenyulu/code/mall-webapp/tsconfig.json'
} +4ms
domain/repository/BaseRepository
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
  vite-tsconfig-paths resolved: {
  id: 'domain/repository/BaseRepository',
  importer: '/Users/chenyulu/code/mall-webapp/src/driver/env/index.ts',
  resolvedId: '/Users/chenyulu/code/mall-webapp/src/domain/repository/BaseRepository.ts',
  configPath: '/Users/chenyulu/code/mall-webapp/tsconfig.json'
} +135ms
domain/repository/BaseRepository
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
domain/service/HomepageService
plugin-vue:export-helper
__vite-browser-external:domain/service/HomepageService
plugin-vue:export-helper
__vite-browser-external:domain/service/HomepageService
__vite-browser-external:domain/service/HomepageService
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
plugin-vue:export-helper
__vite-browser-external:domain/service/HomepageService

This shows that some import statements were handled correctly but some were not.

Breaks with vite-ssg on vercel build

Running build localy works great, but when pushing to vercel it breaks.

00:18:34.586  	vite v2.4.1 building SSR bundle for production... 
00:18:34.633  	 > node_modules/vite-tsconfig-paths/dist/index.js:103:40: error: [plugin: vite:dep-scan] viteResolve is not a function

Avoid picking up tsconfig.json if projects is provided

❯ mv tsconfig.json.bak tsconfig.json

❯ npx vite build -d
✘ [ERROR] Transforming object literal extensions to the configured target environment ("es5") is not supported yet

    vite.config.ts:31:22:
      31 │         assetFileNames(assetInfo) {
         ╵                       ^

  The target environment was set to "es5" here:

    tsconfig.json:4:14:
      4 │     "target": "es5",
        ╵               ~~~~~

failed to load config from /project/vite.config.ts
error during build:
Error: Build failed with 1 error:
vite.config.ts:31:22: ERROR: Transforming object literal extensions to the configured target environment ("es5") is not supported yet

❯ mv tsconfig.json tsconfig.json.bak

❯ npx vite build -d
  vite:config bundled config file loaded in 171.61ms +0ms
  vite-tsconfig-paths options: {
  projects: [
    '/project/tsconfig.vite.json'
  ],
  extensions: [ '.ts', '.tsx', '.js', '.jsx', '.mjs' ]
} +0ms
  vite-tsconfig-paths [!] missing baseUrl and paths: "/project/tsconfig.vite.json" +5ms

As you can see, when tsconfig.json exists it will pick it up, I know it might not be the plugin but vite itself, is there any way to bypass this behaviour?

can not resolve ts files using their corresponding js extesions

Support for .ts to .js alias was added in vite upstream
But it doesn't work with vite-tsconfig-paths:

// from vite.config.ts
  plugins: [
    preact({
      include: '{test/,}src/**/*.{ts,tsx}',
    }),
    !isTest && tsconfigPaths(),
    !isTest &&
      checker({
        typescript: { tsconfigPath: 'src/tsconfig.json' },
        eslint: {
          lintCommand: 'eslint "./src/**/*.{ts,tsx}"',
        },
      }),
    isTest && typescript(),
  ],
// from tsconfig.json

"paths": {
  "@src/*": ["./src/*"],
  "@server/*": ["./server/*"],
  "@test/*": ["./test/*"]
},

Currently I can fix it by:

resolve: {
    alias: [{ find: /^(@.*\/.*)\.js$/, replacement: '$1.ts' }]
}

Repro can be found here:
wight554/blog-template#50

See this issue for more details:
vitejs/vite#7918

Use `exclude` config on `findProjects`

When using this Remix template a folder called postgres-data is created at the root and this plugins tries to scan that folder even if I add it to exclude config.

EACCES: permission denied, scandir '/home/iribeiro/code/ribeirolabs/mecontrole/postgres-data/'
at Object.readdirSync (node:fs:1390:3)
at Object.readdir (/home/iribeiro/code/ribeirolabs/mecontrole/node_modules/recrawl-sync/lib/fs.js:6:25)
at crawl (/home/iribeiro/code/ribeirolabs/mecontrole/node_modules/recrawl-sync/lib/recrawl.js:46:35)
at crawl (/home/iribeiro/code/ribeirolabs/mecontrole/node_modules/recrawl-sync/lib/recrawl.js:67:25)
at /home/iribeiro/code/ribeirolabs/mecontrole/node_modules/recrawl-sync/lib/recrawl.js:85:9
at exports.crawl (/home/iribeiro/code/ribeirolabs/mecontrole/node_modules/recrawl-sync/lib/recrawl.js:15:51)
at findProjects (/home/iribeiro/code/ribeirolabs/mecontrole/node_modules/vite-tsconfig-paths/dist/index.js:210:35)
at Object.configResolved (/home/iribeiro/code/ribeirolabs/mecontrole/node_modules/vite-tsconfig-paths/dist/index.js:68:24)
at /home/iribeiro/code/ribeirolabs/mecontrole/node_modules/vite/dist/node/chunks/dep-9c153816.js:71065:78
at Array.map (<anonymous>) {
  errno: -13,
  syscall: 'scandir',
  code: 'EACCES',
  path: '/home/iribeiro/code/ribeirolabs/mecontrole/postgres-data/'
}

Debugging I found that the folders to skip are hardcoded here https://github.com/aleclarson/vite-tsconfig-paths/blob/master/src/index.ts#L208

We should be allowed to control which folders to skip.

Doesn't work with Eslint

config:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), tsconfigPaths()],
});

tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    },
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": false,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
   "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["./src"]
}

eslintrc.json:

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "plugin:react/recommended",
    "airbnb"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": [
    "react",
    "@typescript-eslint",
    "react-hooks"
  ],
  "rules": {
    "react/react-in-jsx-scope": "off",
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn",
    "react/jsx-filename-extension": [1, { "extensions": [".ts", ".tsx"] }],
    "import/no-extraneous-dependencies": "off",
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "ts": "never",
        "tsx": "never"
      }
   ]
  },
  "settings": {
    "import/extensions": [".ts", ".tsx"],
    "import/parsers": {
      "@typescript-eslint/parser": [".ts", ".tsx"]
    },
    "import/resolver": {
      "node": {
        "extensions": [".ts", ".tsx"]
      }
    }
  }
}

Eslint gives errors:
Missing file extension for "@/App"eslint(import/extensions)
Unable to resolve path to module '@/App'.eslint(import/no-unresolved)

when I try to import using the absolute path. @/

add support for storybook vite

https://github.com/eirslett/storybook-builder-vite

After init, .storybook/main.js

This won't work

const tsconfigPaths = require("vite-tsconfig-paths")

module.exports = {
    stories: [
        "../src/components/**/*.stories.@(ts|tsx)",
    ],
    addons: ["@storybook/addon-links", "@storybook/addon-essentials"],
    core: {
        builder: "storybook-builder-vite",
    },
    async viteFinal(config, { configType }) {
        // customize the Vite config here
        config.resolve.alias.foo = "bar"
        // config.resolve.modules.push(path.resolve(__dirname, "../src"))

        config.plugins = [tsconfigPaths()]

        return config
    },
}

Unable to resolve transitive path

Maintainer note:
See this comment for a solution.


Hey Alec,

I've just given this lib a spin and hit an issue in my mono repo where a mapped path tries to load another module in a mapped path and fails.

Here is the example:

/apps/frontend
/libs/lib1
/libs/lib2

The libs have names/path mappings of @libs/lib1 and @libs/lib2 for instance.

Frontend loads lib1 fine, but lib1 tries to import lib2 and it can't resolve.

I've tracked the issue down to isLocalDescendant. My tsconfig is in /apps/frontend, but because the importer is @libs/lib1 it thinks that lib2 is not a local descendant and it fails to resolve.

Solutions?

I basically need to be able to specify the root as the repo base (ie cwd()), and the tsconfigRoot as two separate options.

Possible non-breaking change, add a baseDir option? Naming is hard, especially with the current value being called root.

Ideas?

Dep optimization failed with error

vite v1.0.0-rc.8
[vite] Optimizable dependencies detected:
core-js, vite-tsconfig-paths, vue

[vite] Dep optimization failed with error:
Dependency vite-tsconfig-paths is attempting to import Node built-in module path.
This will not work in a browser environment.
Imported by: node_modules/vite-tsconfig-paths/dist/index.js

Tip:
Make sure your "dependencies" only include packages that you
intend to use in the browser. If it's a Node.js package, it
should be in "devDependencies".

If you do intend to use this dependency in the browser and the
dependency does not actually use these Node built-ins in the
browser, you can add the dependency (not the built-in) to the
"optimizeDeps.allowNodeBuiltins" option in vite.config.js.

If that results in a runtime error, then unfortunately the
package is not distributed in a web-friendly format. You should
open an issue in its repo, or look for a modern alternative.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Version 3.3.3 broke my app

... while 3.3.2 is still working fine. I'm getting the following error on vite build:

[vite]: Rollup failed to resolve import "@pages/TestPage.vue" from "src/router.ts".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
error during build:
Error: [vite]: Rollup failed to resolve import "@pages/TestPage.vue" from "src/router.ts".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
    at onRollupWarning (/workspaces/test-app/node_modules/vite/dist/node/chunks/dep-1bdbec90.js:46664:19)
    at Object.onwarn (/workspaces/test-app/node_modules/vite/dist/node/chunks/dep-1bdbec90.js:46514:17)
    at Object.onwarn (/workspaces/test-app/node_modules/rollup/dist/shared/rollup.js:19639:20)
    at ModuleLoader.handleResolveId (/workspaces/test-app/node_modules/rollup/dist/shared/rollup.js:18719:26)
    at /workspaces/test-app/node_modules/rollup/dist/shared/rollup.js:18686:22
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async Promise.all (index 1)
    at async ModuleLoader.fetchStaticDependencies (/workspaces/test-app/node_modules/rollup/dist/shared/rollup.js:18684:34)
    at async Promise.all (index 0)
    at async ModuleLoader.fetchModule (/workspaces/test-app/node_modules/rollup/dist/shared/rollup.js:18661:9)

If I run DEBUG=vite-tsconfig-paths yarn vite as suggested in the README, I get the following corresponding error:

 > src/router.ts:3:40: error: No loader is configured for ".vue" files: src/pages/TestPage.vue
    3 │ import TestPage from '@pages/TestPage.vue'
      ╵      

but there are also a number of errors such as

 > html:/workspaces/test-app/src/App.vue:4:23: error: Could not resolve "@components/Card.vue" (the plugin "vite:dep-scan" didn't set a resolve directory)
    4 │ import Card from '@components/Card.vue'
      ╵                  ~~~~~~~~~~~~~~~~~~~~~~

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.