简体   繁体   English

将我的打字稿代码发布到npm时如何处理d.ts文件

[英]How do I deal with d.ts files when publishing my typescript code to npm

I have been following this article: 我一直在关注这篇文章:

How to create strongly-typed npm packages 如何创建强类型的npm软件包

and have been trying to setup my typescript project to publish it to npm. 并一直尝试设置我的打字稿项目以将其发布到npm。

It all seems to make sense but what is not covered is how to deal with d.ts files. 一切似乎都有道理,但没有涉及如何处理d.ts文件。

My project looks somewhat like this: 我的项目看起来像这样:

src
  node
    server.ts
  browser
    client.ts
  common
    contracts.d.ts

so when I compile this with "declaration": true and "outDir: "dist" I get: 所以当我用"declaration": true"outDir: "dist"编译时,我得到:

dist
  node
    server.js
    server.d.ts
  browser
    client.js
    client.d.ts

both my server.ts file and client.ts files have 我的server.ts文件和client.ts文件都有

import {SomeType} from "../common/contracts";

in so when someone else uses this package the typescript compilation will fail as server.d.ts and client.d.ts both still have this import. 因此,当其他人使用此程序包时,由于server.d.tsclient.d.ts都仍具有此导入,因此打字稿编译将失败。

Node will run fine though as client.js and server.js do NOT have this import. 尽管client.jsserver.js没有此导入,但节点将运行良好。 tsc must remove imports of d.ts files. tsc必须删除d.ts文件的导入。

What I want to happen is for the contracts.d.ts file to be copied to the dist folder as part of the build. 我想发生的事情是将contracts.d.ts文件复制到dist文件夹中,作为构建的一部分。 How do I do that as part of the tsc build? tsc构建过程中,我该如何做?

Current Workaround 当前解决方法

What I am currently doing to get round this is rename my contracts.d.ts to just contracts.ts which means that all required files are present in the dist folder but it does mean that both the client and the server are having to load an empty contracts.js file that only contains 为了解决这个问题,我目前正在将我的contracts.d.ts重命名为contracts.ts ,这意味着dist文件夹中存在所有必需的文件,但这确实意味着客户端和服务器都必须加载空的contracts.js文件,仅包含

"use strict";
//# sourceMappingURL=contracts.js.map

I think that I have come up with quite a good solution to this. 我认为我已经提出了一个很好的解决方案。 I have moved my declaration files into a contracts folder so my project looks like this: 我已将申报文件移至合同文件夹,因此我的项目如下所示:

src
  node
    server.ts
  browser
    client.ts
dist
  node
    server.js
    server.d.ts
  browser
    client.js
    client.d.ts
contracts
    common.d.ts

I then just include the contracts folder in the npm package and import files using ../../contracts/common . 然后,我只将合同文件夹包括在npm包中,并使用../../contracts/common导入文件。 This path works both from the src folder when compiling and from the dist folder when building against this package. 此路径在编译时从src文件夹运行,而在针对此软件包构建时从dist文件夹运行。

If though the contracts are just types, I would still declare them in a .ts file. 即使这些合同只是类型,我仍然会在.ts文件中声明它们。 Or are the contracts generated from somewhere else? 还是合同是从其他地方产生的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM