How can I reference typescript files without absolute paths?

前端 未结 2 2031
遥遥无期
遥遥无期 2021-02-18 17:31

Since typescript doesn\'t seem to support absolute path references, I can\'t see how to keep my references tidy. I\'ve got ts files at many different locations in my folder stru

相关标签:
2条回答
  • 2021-02-18 18:12

    There is not currently a way to specify a root folder to use within references.

    Absolute file paths do work, but maintenance of the paths generally speaking with multiple developers makes this likely a non-starter for many TypeScript development projects.

    There have been discussions on CodePlex for example that expressed a similar request (but without a resolution). As TypeScript files are stand-alone, some have been concerned about introducing a "project" like scheme to the compiler.

    Some developers will put the most commonly needed references in a single file (called for example, _references.d.ts) and list references to the definition files there. Then, that file will be referenced from other TypeScript files. It simplifies, but does not completely eliminate the problem (as you still will need to use relative file references with N levels of directory popping potentially):

    /// <references path="../../../_references.d.ts." />
    

    Depending on how many files you have and the size of the definitions though, you may find that as files are individually compiled that the compile process will take longer (as it pulls in potentially unused definitions from the _references.d.ts file). (If you have for example, "compile on save" activated within an IDE).

    0 讨论(0)
  • 2021-02-18 18:21

    In order to keep your relative path references tidy, specify path alias(es) in your tsconfig.json

    First of all install tspath an npm tool for resolving ts paths NOTE: tspath requires a very recent versison of node!

    npm install -g tspath
    

    Next, add path aliases to tsconfig.json

    "baseUrl": "./",
      "paths": {
        "@Scripts/*": ["./Scripts/typings/jquery/*"],
        "@Plugins/*": ["./MyPlugins/V2/*"]
      }
    

    Now use your alias when referencing your scripts

    @Scripts/jquery
    @Plugins/myPlugin
    

    After you have run the TypeScript compiler, from your project directory, run:

    tspath
    

    or

    tspath -f
    

    to skip the prompt!

    Read more at: https://www.npmjs.com/package/tspath

    Hope this is what you asked for!

    0 讨论(0)
提交回复
热议问题