添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
一身肌肉的稀饭  ·  angular - ERROR in ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm trying to do something very similar to the jquery path example in the documentation, but TS keeps throwing TS2307 (webpack compiles fine):

"compilerOptions": {
    "baseUrl": "./src",
    "paths": {
        "@client": [
            "client",
        "@suir": [
            "../node_modules/semantic-ui-react/dist/commonjs", // not working
"include": [
    "*.d.ts",
    "client/**/*",
    "../node_modules/semantic-ui-react", // is this necessary?

Changing baseUrl to "." and updating includes and paths makes no difference (@client continues to work and @suir continues to not work).

Changing "@suir" to "@suir/" or "@suir/*" (and appending /* to its value) also makes no difference.

The reason I'm doing this is to simplify my imports (I'm specifying them explicitly instead of pulling named exports from the bundle in order to reduce my vendor bundle size—saves about 1 MB):

import Button from 'semantic-ui-react/dist/commonjs/elements/Button'; // works
import Button from '@suir/elements/Button'; // not found
                Just wanted to add to this. For me, paths stop working when i use the files property in tsconfig.json. Any solution for this?
– Yashas
                Jan 3, 2021 at 17:46

I have no idea why this is now working on the eleventh time I tried (yet didn't the first 10), but the /* seems to be the secret sauce, and the example in the docs is apparently pointing to a specific file (and the file extension is omitted).

"compilerOptions": { "baseUrl": "./src", // setting a value for baseUrl is required "moduleResolution": "node", // was not set before, but is the default "paths": { "@client/*": [ "client/*", "@suir/*": [ // notice the `/*` at the end "../node_modules/semantic-ui-react/dist/commonjs/*", // notice the `/*` "include": [ "./src/client/**/*", For anyone else still having the problem even though having /* make sure your baseUrl is set, as I just spent hours trying to fix this. – ErraticFox Dec 10, 2018 at 23:06 In case anyone is using VSCode and having trouble getting the /* solution to work. Try Cmd+Shift+P > Typescript: Restart TS Server. – Emily Zhai Dec 5, 2019 at 22:09

As mentioned in the comments by Emily Zhai, this can sometimes just require a language server restart.

In VSCode, you can press Cmd/Ctrl + Shift + P and search for Typescript: Restart TS Server.

After restarting, everything started working for me.

Note that you might need to be in a .ts file for that option to appear. (I had to be focused on a .ts file.) – James Oct 11, 2021 at 19:58 Thank you so so much!! Without this answer I don't know how much more time I would had spent surfing the web to solve this! – DarkCrazy Nov 2, 2022 at 6:26 @DarkCrazy :) It has bitten me multiple times. So many hours wasted on what was just a simple restart – Mitch Talmadge Nov 2, 2022 at 16:07

I did also struggle with .tsconfig not recognizing my aliases (while in another project that supposed to have the save config it worked perfectly).

As it turned out, it was a rookie mistake: I put the paths prop to the end of the JSON object, but it has to be a nested property of the compilerOptions part:

// This does't work ❌
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
     //...
    "baseUrl": ".",
  "include": ["next-env.d.ts", "twin.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"],
  "paths": {
      "@components/*": ["components/*"],
      "@lib/*": ["lib/*"]
// This should work ✅
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
     //...
    "baseUrl": ".",
    "paths": {
      "@components/*": ["components/*"],
      "@lib/*": ["lib/*"]
  "include": ["next-env.d.ts", "twin.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"],
                Glad I could help. I think it's quite counter-intuitive, considering "include" and "exclude" (which are also relative paths) being placed in the object root.
– HynekS
                Nov 17, 2021 at 8:11
                This in combination with the /* magic at the end for BOTH the ALIAS ( @components /* )itself and the path made things work, except images - for those I had to add custom typing files as described here - stackoverflow.com/a/57129153/1835470 basically you create a special file in typings/custom/import-yourextension.d.ts in your project root
– jave.web
                Jan 20, 2022 at 14:38
                Thank you, worked for me! Luckily I found this SO article rather quickly. Interesting: This worked before with Angular 9. With updating to Angular 12, I got Error: Module not found: Error: Can't resolve .... Now it's ok again !
– Rainer Schaack
                Apr 12, 2022 at 10:02

This might help someone - if you use tsc or a tool to compile your TS code to a separate folder such as dist, tsconfig-paths register does NOT work out the box. I have a tsconfig.json like this:

"compilerOptions": { "target": "es5", "module": "commonjs", "lib": ["dom", "esnext"], "baseUrl": ".", "jsx": "react", "removeComments": true, "sourceMap": true, "outDir": "dist" "rootDir": ".", "paths": { "shared/*": ["./shared/*"], "include": ["./client/**/*", "./server/**/*"]

You can see that a path such as shared/someFolder/someScript will resolve correctly to the shared folder in my project, which is a load cleaner than lots of relative ../../../../ paths.

However, this was throwing me the error:

➜  game git:(game-dev) ✗ node --inspect -r tsconfig-paths/register dist/server/runProd.js
Debugger listening on ws://127.0.0.1:9229/f69956aa-d8d6-4f39-8be1-9c3e8383d4be
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
internal/modules/cjs/loader.js:584
    throw err;
Error: Cannot find module 'shared/types/UserTypes'

I did a bit of digging and found that the tryPaths array produced by tsconfig-paths has absolute URLs relative to the project/cwd base, rather than the build dist folder.

This seems obvious in retrospect. There doesn't seem to be an obvious way to handle this with the library, so I have solved this by copying the tsconfig.json into the dist folder and running node -r tsconfig-paths/register main.js.

Out of the box, it doesn't work with tsc or ts-node. But with some packages (tsc-alias & module-alias), it works. No babel or webpack setup are required.

// tsconfig.json
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@common/*": ["common/*"],
      "@services/*": ["services/*"],

Working with TSC

Add tsc-alias (https://www.npmjs.com/package/tsc-alias) as dev dependency

yarn add --dev tsc-alias

And add it to your build command

"build": "tsc && tsc-alias",

Working with TS-NODE

Add module-alias (https://www.npmjs.com/package/module-alias) dependency

yarn add module-alias

Create a file referencing all aliases

// src/paths.ts
import 'module-alias/register';
import { addAliases } from 'module-alias';
addAliases({
  '@common': `${__dirname}/common`,
  '@services': `${__dirname}/services`,

And import it in your entry script as first import

// src/server.ts
import './paths';
import express, { Request, Response, NextFunction } from 'express';
const app = express();
app.listen(port, onListen(port));
                just to mention, for module-alias might be required to install types also:  npm i --save-dev @types/module-alias
– eXception
                Oct 13, 2021 at 12:06

Like, pkestikar said, tsconfig-paths-webpack-plugin can help with that. Save it on devDependencies with yarn add --dev tsconfig-paths-webpack-plugin , add the following configuration on next.config.js

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
module.exports = {
  resolve: {
    plugins: [new TsconfigPathsPlugin({ configFile: "./tsconfig.json" })]

My paths started to work with that. Here's my tsconfig.json

"compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@components/*": ["components/*"]

And here is the import of a component.

import { Button } from '@/components/Button/Button'

It works with just import { Button } from 'components/Button/Button' as well.

After some trial and error, I got to know that, it works differently than we think.

//tsconfig.json
"baseUrl": ".",
"paths": {
  "@components/": ["src/components/"],
//SomeCompomonent.tsx
import { Button } from "@components/" // will work
import Button from "@components/Button" // will not work

to make the second import line work you need to put *

//tsconfig.json
"baseUrl": ".",
"paths": {
  "@components/*": ["src/components/*"],
//SomeCompomonent.tsx
import { Button } from "@components/" // will not work
import Button from "@components/Button" // will work

To make both work

//tsconfig.json
"baseUrl": ".",
"paths": {
  "@components/": ["src/components/"],
  "@components/*": ["src/components/*"],
//SomeCompomonent.tsx
import { Button } from "@components/" // will work
import Button from "@components/Button" // will work

If you are using Vite, you should install vite-tsconfig-paths.

npm i vite-tsconfig-paths --save-dev

Then, 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()],

You may need to restart Vite and/or your TS server after making these changes.

if this is not working check stackoverflow.com/a/74719153/7668448. v4.0.0 have a bug. v4.0.1 fix it. Install with npm install vite-tsconfig-paths@latest – Mohamed Allal Dec 7, 2022 at 15:34

If you are using Webpack with ts-loader and it's still not working after trying all of the answers above, you might need to use a plugin in the resolve section of your Webpack config file - tsconfig-paths-webpack-plugin; so it follows the paths you've put in in your tsconfig.json file while compiling.

Source - https://github.com/TypeStrong/ts-loader#baseurl--paths-module-resolution

I had to use babel to compile the code

npm i -D @babel/cli @babel/core @babel/node @babel/preset-env @babel/preset-typescript babel-plugin-module-resolver

Then on the build command

"build": "babel src --extensions \".js,.ts\" --out-dir dist --copy-files --no-copy-ignored"

And the babel.config.js

module.exports = {
presets: [
        '@babel/preset-env',
            targets: {
                node: 'current'
    '@babel/preset-typescript'
plugins: [
    ['module-resolver', {
        alias: {
            '@config': './src/config',
            '@modules': './src/modules',
            '@shared': './src/shared'
ignore: [
    '**/*.spec.ts'

In my case the issue was that I was adding path to the wrong file. If you are working on a big project where you are not sure of it's configurations, chances are that the config file be extended by other files. In my project there was another file called tsconfig.app.json, notice the extend attribute in the very first row:

"extends": "../tsconfig.json", "compilerOptions": { "paths": { "@angular/*": [ "../node_modules/@angular/*", "@app/*": ["app/*"]

I will recommend, do not change tsconfig.json rather create tconfig.app.json and add following content If already exists then simply add paths, you can reuse your shortPath

Note: its json file so check comma (,) and don't miss or keep extras like in *.ts files

"extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/app", "types": [], "paths": { "@app/*": ["src/app/*"], "@chat/*": ["@app/chat/*"], "@shared/*": ["@app/shared/*"], "@auth/*": ["@app/auth/*"] "files": [ "src/main.ts" "include": [ "src/**/*.d.ts"

On top of Emily Zhai's comment, if someone wants to Restart TypeScript/ESLint Servers Automatically when configs changed on VS Code, my extension may help

Auto Restart TypeScript / ESLint Servers - Visual Studio Marketplace

Check your workspace

Check how you have opened your workspace in VScode.

In my case, I have this structure:

├── my-proyect
│   ├── client* (this is my react folder)
│   └── server

To make it work, I have o open the client folder. If I open the whole project it doesn't work.

Other things to check:

  • tsconfig.json should be something like this
  • "compilerOptions": { "baseUrl": "./src", "paths": { "~/*": ["./*"],
  • vite.config.ts should be something like this (if you use vite)
  • import react from '@vitejs/plugin-react'
    import path from 'path'
    import { defineConfig } from 'vite'
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [react()],
      resolve: {
        alias: {
          '~': path.resolve(__dirname, 'src'),
    

    Restart TS Server.

    In VSCode, you can press **Cmd/Ctrl + Shift + P** and search for Typescript: 
    

    For myself, after much trial and error the solution was simple. Remove this line from my tsconfig and it worked.

    "extends": [
        "plugin:import/recommended",
    
    "rules": {
        "import/no-unresolved": "error",,
                    This is not a solution and just removes the error. If the project is compiling without errors and eslint is still showing an error, then there is a misconfiguration in the eslint config.
    – lachie_h
                    Dec 30, 2021 at 23:25
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.