【问题标题】:tsconfig paths not workingtsconfig 路径不起作用
【发布时间】:2018-11-13 16:44:26
【问题描述】:

我正在尝试做一些与文档中的jquery path example 非常相似的事情,但是 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?
],

baseUrl 更改为"." 并更新includespaths 没有任何区别(@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

【问题讨论】:

  • 只是想补充一下。对我来说,当我使用 tsconfig.json 中的 files 属性时,paths 停止工作。有什么解决办法吗?

标签: typescript alias tsconfig typescript2.9


【解决方案1】:

我不知道为什么这是我第十一次尝试(但不是前 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/**/*",
    ],
}

【讨论】:

  • 对于即使有/* 仍然有问题的其他人,请确保您的baseUrl 已设置,因为我只是花了几个小时试图解决这个问题。
  • 请编辑这篇文章并添加 @ErraticFox 所说的关于 baseUrl 的内容。谢谢!
  • 如果有人在使用 VSCode 并且无法让 /* 解决方案正常工作。试试 Cmd+Shift+P > Typescript: Restart TS Server。
  • @ErraticFox 仍然无法将基本 URL 用作“./”
  • 感谢@EmilyZhai,它帮了我大忙!
【解决方案2】:

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

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

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

【讨论】:

  • 请注意,您可能需要在 .ts 文件中才能显示该选项。 (我必须专注于 .ts 文件。)
【解决方案3】:

这可能对某人有所帮助 - 如果您使用 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/**/*"]
}

您可以看到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'

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

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

【讨论】:

【解决方案4】:

我也曾为.tsconfig 无法识别我的别名而苦恼(而在另一个应该有保存配置的项目中它工作得很好)。

事实证明,这是一个菜鸟错误:我将 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"],
}

【讨论】:

  • 男人!你是救生员!我真的花了 2 天时间来解决这个小错误!
  • 很高兴我能帮上忙。我认为这很违反直觉,考虑到 "include""exclude"(它们也是相对路径)被放置在对象根目录中。
【解决方案5】:

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

// tsconfig.json

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

使用 TSC

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

yarn add --dev tsc-alias

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

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

使用 TS-NODE

添加module-aliashttps://www.npmjs.com/package/module-alias)依赖

yarn add module-alias

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

// src/paths.ts

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

addAliases({
  '@common': `${__dirname}/common`,
  '@services': `${__dirname}/services`,
});

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

// src/server.ts

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

const app = express();
...
app.listen(port, onListen(port));

【讨论】:

  • 只是提一下,module-alias 可能还需要安装类型:npm i --save-dev @types/module-alias
  • 哇!我认为 tsc 可以开箱即用!谢谢你的澄清
【解决方案6】:

就像 pkestikar 说的,tsconfig-paths-webpack-plugin 可以提供帮助。用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" })]
  }
}

我的路径开始与它一起工作。这是我的tsconfig.json

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

这里是一个组件的导入。

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

它也只适用于 import { Button } from 'components/Button/Button'

【讨论】:

    【解决方案7】:

    如果您将Webpackts-loader 一起使用,但在尝试上述所有答案后仍然无法正常工作,您可能需要在Webpack 配置文件的解析部分使用插件 - tsconfig-paths-webpack-plugin;因此它会遵循您在编译时放入 tsconfig.json 文件中的路径。

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

    【讨论】:

      【解决方案8】:

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

      【讨论】:

      • 奇怪,但它有效。我可以确认。这个建议为我节省了很多时间。
      【解决方案9】:

      对我自己来说,经过多次反复试验,解决方案很简单。从我的 tsconfig 中删除这一行,它起作用了。

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

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

      【讨论】:

      • 这不是解决方案,只是消除了错误。如果项目编译没有错误,而 eslint 仍然显示错误,则说明 eslint config 配置错误。
      【解决方案10】:

      我不得不使用 babel 来编译代码

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

      然后在构建命令上

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

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

      }

      【讨论】:

        【解决方案11】:

        如果有人在做了所有提到的事情后仍然有这个问题。尝试关闭 VS 代码并重新打开,环顾四周 2 小时后对我有用..

        【讨论】:

          【解决方案12】:

          就我而言,问题是我添加了错误文件的路径。如果您正在处理一个不确定其配置的大型项目,那么配置文件可能会被其他文件扩展。在我的项目中还有一个名为tsconfig.app.json 的文件,请注意第一行的extend 属性:

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

          【讨论】:

            猜你喜欢
            • 2020-12-23
            • 2022-11-29
            • 2013-07-06
            • 2018-07-26
            • 2020-10-28
            • 2019-01-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多