typescript 如何在 tsconfig.json 中使用路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43281741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:41:04  来源:igfitidea点击:

How to use paths in tsconfig.json?

typescriptnode-modulestsconfig

提问by Remo H. Jansen

I was reading about path-mappingin tsconfig.jsonand I wanted to use it to avoid using the following ugly paths:

我正在阅读有关路径映射的内容tsconfig.json,我想使用它来避免使用以下丑陋的路径:

enter image description here

在此处输入图片说明

The project organization is a bit weird because we have a mono-repository that contains projects and libraries. The projects are grouped by company and by browser / server / universal.

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

enter image description here

在此处输入图片说明

How can I configure the paths in tsconfig.jsonso instead of:

如何配置路径tsconfig.json而不是:

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

I can use:

我可以用:

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

Will something else be required in the webpack config? or is the tsconfig.jsonenough?

webpack 配置中是否还需要其他内容?还是tsconfig.json就够了?

回答by Alejandro Lora

This can be set up on your tsconfig.json file, as it is a TS feature.

这可以在您的 tsconfig.json 文件中设置,因为它是 TS 功能。

You can do like this:

你可以这样做:

"compilerOptions": {
        "baseUrl": "src", // This must be specified if "paths" is.
         ...
        "paths": {
            "@app/*": ["app/*"],
            "@config/*": ["app/_config/*"],
            "@environment/*": ["environments/*"],
            "@shared/*": ["app/_shared/*"],
            "@helpers/*": ["helpers/*"]
        },
        ...

Have in mind that the path where you want to refer to, it takes your baseUrl as the base of the route you are pointing to and it's mandatory as described on the doc.

请记住,您要引用的路径将您的 baseUrl 作为您指向的路线的基础,并且如文档中所述,它是强制性的。

The character '@' is not mandatory.

字符“@”不是必需的。

After you set it up on that way, you can easily use it like this:

以这种方式设置后,您可以轻松地使用它:

import { Yo } from '@config/index';

the only thing you might notice is that the intellisense does not work in the current latest version, so I would suggest to follow an index convention for importing/exporting files.

您可能会注意到的唯一一件事是智能感知在当前最新版本中不起作用,因此我建议遵循索引约定来导入/导出文件。

https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

UPDATECheck out this example I made to showcase how is mapping into a single file:

更新查看我制作的这个示例,以展示如何映射到单个文件中:

https://github.com/ialex90/TypeScript-Node-Starter/commit/a4e8cc1f8f8d5176e0099e05b51f97b0ef4bebea

https://github.com/ialex90/TypeScript-Node-Starter/commit/a4e8cc1f8f8d5176e0099e05b51f97b0ef4bebea

回答by mleko

You can use combination of baseUrland pathsdocs.

您可以使用baseUrlpathsdocs 的组合。

Assuming root is on the topmost srcdir(and I read your image properly) use

假设 root 位于最顶层的src目录(并且我正确读取了您的图像)使用

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

For webpackyou might also need to add module resolution. For webpack2this could look like

因为webpack您可能还需要添加模块分辨率。因为webpack2这可能看起来像

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

回答by AgBorkowski

Check this similar solutions with asterisk

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

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

回答by James Moran

Alejandros answer worked for me, but as I'm using the awesome-typescript-loaderwith webpack 4, I also had to add the tsconfig-paths-webpack-pluginto my webpack.config file for it to resolve correctly

Alejandros 的回答对我awesome-typescript-loader有用,但是当我使用webpack 4 时,我还必须将它添加tsconfig-paths-webpack-plugin到我的 webpack.config 文件中才能正确解析

回答by Joon

If you are using paths, you will need to change back absolute paths to relative paths for it to work after compiling typescript into plain javascript using tsc.

如果您使用路径,则需要将绝对路径改回相对路径,以便在使用tsc.

Most popular solution for this has been tsconfig-pathsso far.

到目前为止,最流行的解决方案是tsconfig-paths

I've tried it, but it did not work for me for my complicated setup. Also, it resolves paths in run-time, meaning overhead in terms of your package size and resolve performance.

我试过了,但它对我的复杂设置不起作用。此外,它在运行时解析路径,这意味着包大小和解析性能方面的开销。

So, I wrote a solution myself, tscpaths.

所以,我自己写了一个解决方案,tscpaths

I'd say it's better overall because it replaces paths at compile-time. It means there is no runtime dependency or any performance overhead. It's pretty simple to use. You just need to add a line to your build scripts in package.json.

我会说它总体上更好,因为它在编译时替换了路径。这意味着没有运行时依赖性或任何性能开销。使用起来非常简单。你只需要在你的构建脚本中添加一行package.json

The project is pretty young, so there could be some issues if your setup is very complicated. It works flawlessly for my setup, though my setup is fairly complex.

该项目还很年轻,因此如果您的设置非常复杂,可能会出现一些问题。它对我的设置完美无缺,尽管我的设置相当复杂。

回答by eeglbalazs

if typescript + webpack 2 + at-loader is being used, there is an additional step (@mleko's solution was only partially working for me):

如果正在使用 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 } */)
    ]
}

Advanced path resolution in TypeScript 2.0

TypeScript 2.0 中的高级路径解析

回答by Vijay

Its kind of relative path Instead of the below code

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

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

We can avoid the "../../../../../" its looking odd and not readable too.

我们可以避免 "../../../../../" 它看起来很奇怪而且不可读。

So Typescript config file have answer for the same. Just specify the baseUrl, config will take care of your relative path.

所以 Typescript 配置文件有相同的答案。只需指定 baseUrl,config 将处理您的相对路径。

way to config:tsconfig.json file add the below properties.

配置方式:tsconfig.json 文件添加以下属性。

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

So Finally it will look like below

所以最后它看起来像下面

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

Its looks simple,awesome and more readable..

它看起来简单,很棒,更易读..

回答by FacePalm

This works for me:

这对我有用:

 yarn add --dev tsconfig-paths

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

This loads all paths in tsconfig.json. A sample tsconfig.json:

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

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

Make sure you have both baseUrl and paths for this to work

确保你有 baseUrl 和路径才能工作

And then you can import like :

然后你可以像这样导入:

import {AlarmIcon} from 'assets/icons'

回答by divya_kanak

Checkout the compiler operation using this

使用检查编译器操作

I have added baseUrl in the file for a project like below :

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

"baseUrl": "src"

"baseUrl": "src"

It is working fine. So add your base directory for your project.

它工作正常。因此,为您的项目添加基本目录。

回答by Andy Braham

It looks like there has been an update to React that doesn't allow you to set the "paths"in the tsconfig.jsonanylonger.

它看起来像已有反应,不允许你设置的更新"paths"tsconfig.jsonanylonger。

Nicely React just outputs a warning:

Nicely React 只是输出一个警告:

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

then updates your tsconfig.jsonand removes the entire "paths"section for you. There is a way to get around this run

然后更新您的tsconfig.json"paths"为您删除整个部分。有一种方法可以绕过这个运行

npm run eject

This will eject all of the create-react-scriptssettings by adding configand scriptsdirectories and build/config files into your project. This also allows a lot more controlover how everything is built, named etc. by updating the {project}/config/*files.

这将弹出所有的create-react-scripts通过增加设置configscripts目录,并建立/配置文件到您的项目。这还允许通过更新文件对所有内容的构建、命名等方式进行更多控制{project}/config/*

Then update your tsconfig.json

然后更新你的 tsconfig.json

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