简体   繁体   English

为什么这些 tsconfig 路径不起作用?

[英]Why are these tsconfig paths not working?

I'm trying to do something very similar to the jquery path example in the documentation, but TS keeps throwing TS2307 (webpack compiles fine):我正在尝试做一些与文档中的jquery 路径示例非常相似的事情,但 TS 一直抛出TS2307 (webpack 编译正常):

"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 "."baseUrl更改为"." and updating includes and paths makes no difference ( @client continues to work and @suir continues to not work).并且更新includespaths没有区别( @client继续工作而@suir继续不工作)。

Changing "@suir" to "@suir/" or "@suir/*" (and appending /* to its value) also makes no difference."@suir"更改为"@suir/"或“@suir "@suir/*" (并将/*附加到其值)也没有区别。


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):我这样做的原因是为了简化我的导入(我明确指定它们而不是从包中提取命名导出以减少我的供应商包大小——节省大约 1 MB):

import Button from 'semantic-ui-react/dist/commonjs/elements/Button'; // works

import Button from '@suir/elements/Button'; // not found

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).我不知道为什么这是我第十一次尝试(但不是前 10 次),但/*似乎是秘诀,文档中的示例显然指向特定文件(并且省略了文件扩展名)。

{
    "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/**/*",
    ],
}

As mentioned in the comments by Emily Zhai , this can sometimes just require a language server restart.正如Emily Zhai的评论中提到的,这有时只需要重启语言服务器。

In VSCode, you can press Cmd/Ctrl + Shift + P and search for Typescript: Restart TS Server .在 VSCode 中,您可以按Cmd/Ctrl + Shift + P并搜索Typescript: Restart TS Server

After restarting, everything started working for me.重新启动后,一切都开始为我工作。

I did also struggle with .tsconfig not recognizing my aliases (while in another project that supposed to have the save config it worked perfectly).我也确实为.tsconfig无法识别我的别名而苦苦挣扎(而在另一个应该具有保存配置的项目中它工作得很好)。

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:事实证明,这是一个新手错误:我将paths属性放在 JSON 对象的末尾,但它必须是compilerOptions部分的嵌套属性:

// 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"],
}

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.这可能会对某人有所帮助 - 如果您使用tsc或工具将您的 TS 代码编译到单独的文件夹(例如dist ), tsconfig-paths寄存器无法解决问题。 I have a tsconfig.json like this:我有一个这样的 tsconfig.json:

{
    "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.您可以看到诸如shared/someFolder/someScript之类的路径将正确解析为我项目中的shared文件夹,这比许多相对../../../../路径更容易加载。

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.我做了一些挖掘,发现 tsconfig-paths 生成的tryPaths数组具有相对于project /cwd 基础的绝对 URL,而不是 build dist文件夹。

检查屏幕截图

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 .似乎没有明显的方法来处理这个库,所以我通过将tsconfig.json复制到dist文件夹并运行node -r tsconfig-paths/register main.js解决了这个问题。

Out of the box, it doesn't work with tsc or ts-node.开箱即用,它不适用于 tsc 或 ts-node。 But with some packages (tsc-alias & module-alias), it works.但是对于某些软件包(tsc-alias 和 module-alias),它可以工作。 No babel or webpack setup are required.不需要 babel 或 webpack 设置。

// tsconfig.json

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

Working with TSC与 TSC 合作

Add tsc-alias ( https://www.npmjs.com/package/tsc-alias ) as dev dependency添加tsc-alias ( https://www.npmjs.com/package/tsc-alias ) 作为开发依赖

yarn add --dev tsc-alias

And add it to your build command并将其添加到您的构建命令中

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

Working with TS-NODE使用 TS-NODE

Add module-alias ( https://www.npmjs.com/package/module-alias ) dependency添加模块别名https://www.npmjs.com/package/module-alias )依赖

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));

Like, pkestikar said, tsconfig-paths-webpack-plugin can help with that.就像,pkestikar 说, tsconfig-paths-webpack-plugin可以帮助解决这个问题。 Save it on devDependencies with yarn add --dev tsconfig-paths-webpack-plugin , add the following configuration on next.config.js使用yarn add --dev tsconfig-paths-webpack-plugin将其保存在 devDependencies 上,在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这是我的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.它也适用于import { Button } from 'components/Button/Button'

If someone still has this issue even after doing everything mentioned.如果有人在做了所有提到的事情之后仍然有这个问题。 Try close down VS code and reopen again, that worked for me 2 hours after looking around..尝试关闭 VS 代码并再次重新打开,环顾四周 2 小时后对我有用..

即使设置了基本 url,检查它是否在默认值“./”然后应该更改为“src”,只有这种方式对我有用。

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 ;如果您正在使用带有ts-loaderWebpack ,但在尝试了上述所有答案后仍然无法正常工作,您可能需要在Webpack配置文件的解析部分使用插件 - tsconfig-paths-webpack-plugin so it follows the paths you've put in in your tsconfig.json file while compiling.因此它遵循您在编译时放入tsconfig.json文件的路径。

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

While trying to make tsconfig work, the following command proved very helpful:在尝试使 tsconfig 工作时,以下命令被证明非常有用:

 npx tsc --showConfig

This will output some json with the files field showing the actual recognized files by your configuration.这将 output 和 json files字段显示您的配置实际识别的文件。

For myself, after much trial and error the solution was simple.对我自己来说,经过多次试验和错误,解决方案很简单。 Remove this line from my tsconfig and it worked.从我的 tsconfig 中删除这一行,它起作用了。

"extends": [
    "plugin:import/recommended",
]

and

"rules": {
    "import/no-unresolved": "error",,
}

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:在我的项目中,还有一个名为tsconfig.app.json的文件,请注意第一行的 extend 属性:

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

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 .如果你使用 Vite,你应该安装vite-tsconfig-paths

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

Then, inject vite-tsconfig-paths using the vite.config.ts module然后,使用vite.config.ts模块注入vite-tsconfig-paths

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.进行这些更改后,您可能需要重新启动 Vite 和/或您的 TS 服务器。

Try add in tsConfig.json the follow property inside CompileOptions:尝试在 tsConfig.json 中添加 CompileOptions 中的以下属性:

"baseUrl": "." “baseUrl”:“。”

In my case working.在我的情况下工作。

Make sure the path provided is correct.确保提供的路径正确。 It will throw error "module and its decrations not found".它将抛出错误“未找到模块及其声明”。

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我会建议,不要更改tsconfig.json而是创建tconfig.app.json并添加以下内容如果已经存在则只需添加路径,您可以重用您的shortPath

Note: its json file so check comma (,) and don't miss or keep extras like in * .ts files注意:它的 json 文件所以检查逗号 (,) 并且不要遗漏或保留 * .ts文件中的额外内容


{
  "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 helpEmily Zhai 的评论之上,如果有人想在 VS Code 上的配置更改时自动重启 TypeScript/ESLint 服务器,我的扩展可能会有所帮助

Auto Restart TypeScript / ESLint Servers - Visual Studio Marketplace 自动重启 TypeScript / ESLint 服务器 - Visual Studio Marketplace

I had to use babel to compile the code我不得不使用 babel 来编译代码

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还有 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'
]

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM