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

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

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

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

我可以使用:

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

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


当前回答

这对我来说很管用:

 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'

其他回答

您可以通过使用子路径模式仅使用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/*"],
        },
    },
}

如果你正在使用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....

对于组件库

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

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

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

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

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

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

// webpack.config.js
module.exports = {
    resolve: {
        ...
        modules: [
            ...
            './src/org/global'
        ]
    }
}
{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

我不确定我们是否必须定义路径。但是在将baseUrl写入src之后 我可以像这样导入SRC文件夹下的所有文件夹

import { Home } from "pages";
import { formatDate } from "utils";
import { Navbar } from "components";

不要忘记在修改tsconfig.json后重新启动您的终端