Typescript does not copy d.ts files to build

前端 未结 1 898
半阙折子戏
半阙折子戏 2020-12-03 05:16

So maybe I\'m confused, but I thought that if I added declaration:true to my tsconfig.json I could have it tsc copy my *.d.ts files, along side the

相关标签:
1条回答
  • 2020-12-03 06:03

    You are right - declaration:true implies that only for each given .ts file tsc generates and copies a corresponding .d.ts output file to the build directory (in addition to .js and .map if applicable). So tsc will not copy your custom types.d.ts file to the output directory.

    Basically .d.ts files are seen as untouchable input for the compiler to do type checks. They are not used for any output generation, which also means, they do not get copied over to build. You can read more here about the maintainers' standpoint:

    The .d.ts files you use are an input to the build system but not an output. It's perfectly reasonable to consume some types from a .d.ts but have your output not use those types, so there'd be no reason to distribute the input .d.ts with your build results. [...] It sounds like you'll want a post-build step in your build tool to copy the relevant .d.ts files wherever you need them.

    The .d.ts files are considered "references" the compiler will not touch them, not move them, or recreate them. An easy way to think of the .d.ts files is that they go along with your .js files. if you are copying the .js files, you should copy the matching .d.ts.

    Solution #1: Copy d.ts files via manual build step

    A possible solution is to copy all needed .d.ts files like types.d.ts manually in a build step. The concrete tool is preference and dependents on your project and build type, OS amongst others. This tool should preserve the directory structure under src when copying files to build, so that import type references still work. To name a few: cp --parents (shell), rsync, robocopy or a platform independent npm package like copyfiles:

    "scripts": {
      "copy-dts": "copyfiles -u 1 \"src/**/*.d.ts\" build"
    }
    

    Solution #2: Reword d.ts files to .ts extension

    Reword your .d.ts files to .ts extension (or re-integrate the types into existent .ts files), so tsc takes care of emitting the declarations in the output. Slight disadvantage: You have no compiler enforced separation between types and implementation code (d.ts files are not allowed to contain code). Big advantage is, you don't need an additional build step.

    In my opinion, the latter is the easiest approach to generate a public API e.g. for your npm package, whereas a .d.ts file could make a candidate for an internally used and shared type declaration.

    Hope, that helps.

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