tsconfig路径无法正常工作

jac*_*cob 11 alias typescript tsconfig typescript2.9

我正在尝试做一些非常类似于文档中的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?
],
Run Code Online (Sandbox Code Playgroud)

更改baseUrl"."和更新includes,并paths没有什么区别(@client继续工作,@suir继续到不行).

更改"@suir""@suir/""@suir/*"(和附加/*到它的价值)也没有什么区别.


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

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

import Button from '@suir/elements/Button'; // not found
Run Code Online (Sandbox Code Playgroud)

Mit*_*dge 19

正如Emily Zhai在评论中提到的,这有时只需要重新启动语言服务器。

在 VSCode 中,您可以按Cmd/Ctrl + Shift + P并搜索Typescript: Restart TS Server

重新启动后,一切都开始为我工作。

  • 请注意,您可能需要位于 .ts 文件中才能显示该选项。(我必须专注于 .ts 文件。) (6认同)

Hug*_*eth 17

这可能帮助别人-如果你使用tsc或工具编译你的TS的代码到一个单独的文件夹,例如disttsconfig-paths注册不开箱。我有一个像这样的 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/**/*"]
}
Run Code Online (Sandbox Code Playgroud)

您可以看到,诸如此类的路径shared/someFolder/someScript将正确解析为shared我项目中的文件夹,这比许多相对../../../../路径更负载清洁。

但是,这给我带来了错误:

?  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'
Run Code Online (Sandbox Code Playgroud)

我做了一些挖掘,发现tryPathstsconfig-paths 生成的数组具有相对于project/cwd 基的绝对 URL ,而不是构建dist文件夹。

检查屏幕截图

回想起来,这似乎很明显。似乎没有明显的方法可以用库来处理这个问题,所以我通过将 复制tsconfig.jsondist文件夹中并运行node -r tsconfig-paths/register main.js.

  • 很好的解释!相关 Github 问题:https://github.com/dividab/tsconfig-paths/issues/75 (2认同)

jac*_*cob 13

我不知道为什么现在这是我第十一次尝试(但没有前10个),但/*似乎是秘密的酱,文档中的示例显然指向一个特定的文件(和文件扩展名被省略).

{
    "compilerOptions": {
        "baseUrl": "./src",
        "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/**/*",
    ],
}
Run Code Online (Sandbox Code Playgroud)

  • 如果有人在使用 VSCode 时遇到“/*”解决方案无法正常工作的情况。尝试 Cmd+Shift+P > Typescript:重新启动 TS 服务器。 (53认同)
  • 对于即使拥有`/ *仍然有问题的其他人,请确保已设置`baseUrl`,因为我花了数小时试图解决此问题。 (7认同)
  • @EmilyZhai 我❤️你 (6认同)
  • @ErraticFox 仍然无法使用基本 url 作为“./” (4认同)

小智 10

经过一番尝试和错误后,我发现它的工作原理与我们想象的不同。

//tsconfig.json
"baseUrl": ".",
"paths": {
  "@components/": ["src/components/"],
}

//SomeCompomonent.tsx
import { Button } from "@components/" // will work
import Button from "@components/Button" // will not work
Run Code Online (Sandbox Code Playgroud)

要使第二条导入线工作,您需要放置*

//tsconfig.json
"baseUrl": ".",
"paths": {
  "@components/*": ["src/components/*"],
}

//SomeCompomonent.tsx
import { Button } from "@components/" // will not work
import Button from "@components/Button" // will work
Run Code Online (Sandbox Code Playgroud)

为了让两者都工作

//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
Run Code Online (Sandbox Code Playgroud)


小智 9

就像 pkestikar 说的那样,tsconfig-paths-webpack-plugin可以帮助解决这个问题。保存在 devDependencies 上yarn add --dev tsconfig-paths-webpack-plugin ,添加以下配置next.config.js

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')

module.exports = {
  resolve: {
    plugins: [new TsconfigPathsPlugin({ configFile: "./tsconfig.json" })]
  }
}
Run Code Online (Sandbox Code Playgroud)

我的道路开始与此相关。这是我的tsconfig.json

"compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@components/*": ["components/*"]
    },
}
Run Code Online (Sandbox Code Playgroud)

这里是一个组件的导入。

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

它也同样适用import { Button } from 'components/Button/Button'


Hyn*_*ekS 8

我也确实.tsconfig无法识别我的别名(而在另一个应该具有保存配置的项目中,它可以完美运行)。

事实证明,这是一个菜鸟错误:我将pathsprop放在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/*"]
    }
}
Run Code Online (Sandbox Code Playgroud)
// 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"],
}
Run Code Online (Sandbox Code Playgroud)

  • 男人!你是救星!我真的花了两天时间来解决这个小错误! (13认同)
  • 天哪,我已经找这个了 3 个小时了,我快疯了 (3认同)

use*_*948 8

如果您使用 Vite,则应该安装vite-tsconfig-paths

npm i vite-tsconfig-paths --save-dev
Run Code Online (Sandbox Code Playgroud)

然后,vite-tsconfig-paths使用vite.config.ts模块注入

npm i vite-tsconfig-paths --save-dev
Run Code Online (Sandbox Code Playgroud)

进行这些更改后,您可能需要重新启动 Vite 和/或 TS 服务器。


小智 7

在尝试使 tsconfig 工作时,以下命令被证明非常有用:

npx tsc --showConfig
Run Code Online (Sandbox Code Playgroud)

这将输出一些 json,其中的字段files显示您的配置实际识别的文件。


Cam*_*CHN 6

开箱即用,它不适用于 tsc 或 ts-node。但是对于一些包(tsc-alias 和 module-alias),它可以工作。不需要 babel 或 webpack 设置。

// tsconfig.json

{
  "compilerOptions": {
    ...
    "baseUrl": "./src",
    "paths": {
      "@common/*": ["common/*"],
      "@services/*": ["services/*"],
    },
    ...
  },
}
Run Code Online (Sandbox Code Playgroud)

与 TSC 合作

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

yarn add --dev tsc-alias
Run Code Online (Sandbox Code Playgroud)

并将其添加到您的构建命令中

"build": "tsc && tsc-alias",
Run Code Online (Sandbox Code Playgroud)

使用 TS-NODE

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

yarn add module-alias
Run Code Online (Sandbox Code Playgroud)

创建一个引用所有别名的文件

// src/paths.ts

import 'module-alias/register';
import { addAliases } from 'module-alias';

addAliases({
  '@common': `${__dirname}/common`,
  '@services': `${__dirname}/services`,
});
Run Code Online (Sandbox Code Playgroud)

并将其作为第一次导入导入到您的入口脚本中

// src/server.ts

import './paths';
import express, { Request, Response, NextFunction } from 'express';
...

const app = express();
...
app.listen(port, onListen(port));
Run Code Online (Sandbox Code Playgroud)

  • 哇!我以为 tsc 可以开箱即用!谢谢你的澄清 (3认同)

Tob*_*in2 5

如果有人在完成上述所有操作后仍然遇到此问题。尝试关闭 VS code 并再次重新打开,这对我环顾四周后 2 小时有效。