我正在阅读tsconfig中的路径映射。json,我想用它来避免使用以下丑陋的路径:

项目组织有点奇怪,因为我们有一个包含项目和库的单一存储库。项目按公司和浏览器/服务器/通用进行分组。

如何配置tsconfig中的路径?Json,而不是:

import { Something } from "../../../../../lib/src/[browser/server/universal]/...";

我可以使用:

import { Something } from "lib/src/[browser/server/universal]/...";

webpack配置中还需要其他东西吗?或者是tsconfig。json足够了吗?


当前回答

您可以通过使用子路径模式仅使用Node来实现这一点。

例如,将此添加到package.json…

{
    "imports": {
        "#lib": "./build/path/to/lib",
        "#lib/*": "./build/path/to/lib/*",
    }
}

...会让你像这样导入,避免相对路径。

import { something } from "#lib"

注意,它们必须以散列开头,并且在package中。json,它们必须指向你的构建,这样Node才能识别它。

正如其他人所说,您可以在tsconfig中添加这样的内容。json for Typescript:

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "#lib": ["./src/path/to/lib"],
            "#lib/*": ["./src/path/to/lib/*"],
        },
    },
}

其他回答

这对我来说很管用:

 yarn add --dev tsconfig-paths

 ts-node -r tsconfig-paths/register <your-index-file>.ts

这将加载tsconfig.json中的所有路径。tsconfig.json示例:

{
    "compilerOptions": {
        {…}
        "baseUrl": "./src",
        "paths": {
            "assets/*": [ "assets/*" ],
            "styles/*": [ "styles/*" ]
        }
    },
}

确保你有baseUrl和路径来工作

然后你可以像这样导入:

import {AlarmIcon} from 'assets/icons'

/只从根目录开始,为了获得相对路径,我们应该使用./或../

对于组件库

如果你正在处理一个返回UI组件的库(如react-bootstrap或antd),那么这应该适合你。

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

用星号检查类似的解决方案

  "baseUrl": ".",
  "paths": {
    "*": [
      "node_modules/*",
      "src/types/*"
    ]
  },

如果你正在寻找用@引用根文件夹的最简单的例子,这将是它:

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@/*": ["*"]
    }
  }
}
// Example usage: import * as logUtils from '@/utils/logUtils';

或者如果你甚至没有src文件夹,或者想要显式地将它包含在导入中,这也可以工作:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["*"]
    }
  }
}
// Example usage: import * as logUtils from '@/src/utils/logUtils';