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

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

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

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

我可以使用:

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

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


当前回答

如果typescript + webpack 2 + at-loader正在使用,有一个额外的步骤(@mleko的解决方案只部分适用于我):

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

// webpack.config.js
const { TsConfigPathsPlugin } = require('awesome-typescript-loader');

resolve: {
    plugins: [
        new TsConfigPathsPlugin(/* { tsconfig, compiler } */)
    ]
}

TypeScript 2.0中的高级路径解析

其他回答

使用这个检出编译器操作

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

“baseUrl " src "

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

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

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]/...";

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

确保你有 ` { “compileOnSave”:没错, " compilerOptions ": { "路径":{ “@styles /”:(“资产/ scss /”) } }, }

` 这给我带来了麻烦。

正确是很重要的。

import Home from '@app/features/Home';

src /功能/ Home.tsx

  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@app/*": [
        "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'
        ]
    }
}