TypeScript 导入路径别名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38601592/
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:14:59  来源:igfitidea点击:

TypeScript Import Path Alias

typescripttypescript2.0

提问by Dwayne Charrington

I am currently working on a TypeScript application which is comprised of multiple Node modules written in TypeScript, that are installed into the node_modulesdirectory.

我目前正在开发一个 TypeScript 应用程序,它由多个用 TypeScript 编写的 Node 模块组成,这些模块安装到node_modules目录中。

Before continuing, I would like to note that I am using TypeScript 2.0, I am not adverse to using the 2.1 dev release if need be as well. I just want to get this working.

在继续之前,我想指出我使用的是 TypeScript 2.0,如果需要的话,我也不反对使用 2.1 开发版。我只是想让这个工作。

The structure of each Node module is something along the lines of:

每个 Node 模块的结构大致如下:

dist/
    es2015/
        index.js
        utils/
            Calculator.js
            Calculator.d.ts
            Date.js
            Date.d.ts
            Flatpack.js
            Flatpack.d.ts
src/
    index.ts
    utils/
        Calculator.ts
        Date.ts
        Flatpack.ts

The dist folder is the generated source, with this path being configured using outDirinside of my tsconfig.jsonfile. I have also configured the mainproperty in my package.jsonto be dist/es2015/index.js.

dist 文件夹是生成的源,使用outDir我的tsconfig.json文件内部配置此路径。我还将我的main属性配置package.jsondist/es2015/index.js.

Important things to note:

需要注意的重要事项:

  • In my project I am using moduleResolutiontype of node
  • I am using TypeScript 2.0
  • I am not asking how to import a file from within the package. I am installing the package via Npm and then importing it via packagename/from within an application that is using this module.
  • 在我的项目中,我使用的moduleResolution类型node
  • 我正在使用 TypeScript 2.0
  • 我不是在问如何从包中导入文件。我正在通过 Npm 安装包,然后通过packagename/从使用此模块的应用程序中导入它。

Now comes my question/issue. Whilst importing files from this module, I would like to be able to do this:

现在是我的问题/问题。在从此模块导入文件时,我希望能够执行以下操作:

import {Sin, Cos, Tan} from "common-utils/utils/Calculator";

However, the file cannot resolve to the dist/es2015/utilsdirectory. Ideally I would like my imports to resolve from this specific distfolder and not from the root, which is what appears to be happening.

但是,该文件无法解析到该dist/es2015/utils目录。理想情况下,我希望我的导入从这个特定dist文件夹而不是从根目录解析,这似乎正在发生。

The above import needs to be written as the following to get it to work:

需要将上述导入编写如下才能使其工作:

import {Sin, Cos, Tan} from "common-utils/dist/es2015/utils/Calculator";

However, writing dist/es2015each time is not ideal and it just makes some of the imports look really long. Is there a way I can configure my module to resolve to the dist/es2015directory? I don't want to have to put in overrides inside of my project, ideally each module would specify where files are resolved from.

但是,dist/es2015每次写入并不理想,它只会使某些导入看起来很长。有没有办法可以配置我的模块以解析到dist/es2015目录?我不想在我的项目中放置覆盖,理想情况下每个模块都会指定文件的解析位置。

If you are still unsure what I am asking (and I apologise if this is confusing) in Jspm when you create a plugin/module to be used with Jspm, you can specify inside of the package.jsonfor the module something like the following:

如果您在创建与 Jspm 一起使用的插件/模块时仍然不确定我在 Jspm 中要问什么(如果这令人困惑,我深表歉意),您可以package.json在模块内部指定如下内容:

  "jspm": {
    "registry": "npm",
    "jspmPackage": true,
    "main": "my-module",
    "format": "amd",
    "directories": {
      "dist": "dist/amd"
    },

I am looking for the equivalent of the above in TypeScript (if it exists). A mapping directive, so when the end user runs npm install my-cool-packageand then in their app tries to import something, all imports by default resolve to the commonjsdirectory (the above example for Jspm uses amd, but same premise).

我正在寻找 TypeScript 中的上述等效项(如果存在)。一个映射指令,因此当最终用户运行npm install my-cool-package然后在他们的应用程序中尝试导入某些内容时,所有导入默认解析为commonjs目录(上面的 Jspm 示例使用 amd,但前提相同)。

Is this possible or am I misunderstanding something here? I know some new path mapping features were added into the latest release, but documentation on using them is almost nonexistent.

这是可能的还是我在这里误解了什么?我知道最新版本中添加了一些新的路径映射功能,但几乎没有使用它们的文档。

回答by fny

So after reading your comment, I realized I misunderstood your question! If you want to control the paths from an imported package's perspective, just use set the mainproperty of your package.jsonto a file that properly represents the object graph of your module.

因此,在阅读您的评论后,我意识到我误解了您的问题!如果您想从导入的包的角度控制路径,只需使用将main您的属性设置为package.json正确表示模块对象图的文件。

{
  "main": "common-utils/dist/es2015/index.js"
}

If you're attempting to control the import paths from a project's perspective, what you're looking for is TypeScript 2's new path mapping feature for module resolution. You can enable path mapping by configuring your tsconfig.jsonas follows:

如果您试图从项目的角度控制导入路径,那么您正在寻找的是 TypeScript 2 用于模块解析的新路径映射功能。您可以通过tsconfig.json如下配置来启用路径映射:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "angular2/*": ["../path/to/angular2/*"],
      "local/*": ["../path/to/local/modules/*"]
    }
  }
}

Then, in your TypeScript files, you can import the modules like this:

然后,在您的 TypeScript 文件中,您可以像这样导入模块:

import { bootstrap } from 'angular2/bootstrap';
import { module } from 'local/module';

For more details about the Path Mapping feature in TypeScript 2 see this Github issue.

有关 TypeScript 2 中路径映射功能的更多详细信息,请参阅此 Github 问题

In your case, I think the following configuration should work:

在您的情况下,我认为以下配置应该有效:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "common-utils/utils/*": ["./node_modules/common-utils/dist/es2015/utils/*"]
    }
  }
}

回答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.

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