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

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

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

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

我可以使用:

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

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


当前回答

这是相对路径 而不是下面的代码

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

我们可以避免“../../../../.. .”/“它看起来很奇怪,也不容易读。

Typescript配置文件有相同的答案。 只要指定baseUrl,配置就会照顾你的相对路径。

配置方法:tsconfig。Json文件添加以下属性。

"baseUrl": "src",
    "paths": {
      "@app/*": [ "app/*" ],
      "@env/*": [ "environments/*" ]
    }

最终会像下面这样

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

它看起来简单,令人敬畏,更可读。

其他回答

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

{
  "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';

如果你正在使用tsconfig-paths,这对你不起作用,试试tsconfig.json:

{
  // ...
  "compilerOptions": {
    "outDir": "dist",
    "rootDir": "src",
    "baseUrl": ".",
    "paths": {
      "@some-folder/*": ["./src/app/some-folder/*", "./dist/app/some-folder/*"],
      // ...
    }
  },
  // ...
}

如果编译器看到@some-folder/some-class,它会试图在./src…或在。/dist....

使用这个检出编译器操作

我在文件中添加了baseUrl项目如下:

“baseUrl " src "

它工作得很好。因此,为项目添加基本目录。

你可以结合使用baseUrl和路径文档。

假设根在最上面的src目录(我正确地阅读了你的图像)使用

// tsconfig.json
{
  "compilerOptions": {
    ...
    "baseUrl": ".",
    "paths": {
      "lib/*": [
        "src/org/global/lib/*"
      ]
    }
  }
}

对于webpack,你可能还需要添加模块解析。对于webpack2,这可能是这样的

// webpack.config.js
module.exports = {
    resolve: {
        ...
        modules: [
            ...
            './src/org/global'
        ]
    }
}

看起来React已经更新了,不允许你在tsconfig中设置“路径”。json anylonger。

nice React只输出一个警告:

The following changes are being made to your tsconfig.json file:
  - compilerOptions.paths must not be set (aliased imports are not supported)

然后更新您的tsconfig。Json,并为您删除整个“路径”部分。有个办法可以绕过这条路

npm run eject

这将通过添加配置和脚本目录以及build/config文件到您的项目中,弹出所有的create-react-scripts设置。这也允许通过更新{project}/config/*文件来对所有内容的构建、命名等进行更多的控制。

然后更新tsconfig.json

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