TypeScript Import Path Alias

后端 未结 2 691
情书的邮戳
情书的邮戳 2020-11-28 06:40

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

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 07:11

    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 main property of your package.json to a file that properly represents the object graph of your module.

    {
      "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.json as follows:

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

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

    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.

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

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

提交回复
热议问题