4

I have been following this article:

How to create strongly-typed npm packages

and have been trying to setup my typescript project to publish it to npm.

It all seems to make sense but what is not covered is how to deal with d.ts files.

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:

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

both my server.ts file and client.ts files have

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.

Node will run fine though as client.js and server.js do NOT have this import. tsc must remove imports of d.ts files.

What I want to happen is for the contracts.d.ts file to be copied to the dist folder as part of the build. How do I do that as part of the tsc build?

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

"use strict";
//# sourceMappingURL=contracts.js.map
Community
  • 1
  • 1
Roaders
  • 4,373
  • 8
  • 50
  • 71

2 Answers2

3

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. This path works both from the src folder when compiling and from the dist folder when building against this package.

Roaders
  • 4,373
  • 8
  • 50
  • 71
0

If though the contracts are just types, I would still declare them in a .ts file. Or are the contracts generated from somewhere else?

mweststrate
  • 4,890
  • 1
  • 16
  • 26
  • They are just types but interfaces do not result in a JavaScript file so you put them in a .d.ts file to indicate to the compiler that it should not produce a js file. – Roaders Nov 21 '16 at 09:16
  • interfaces never result in javascript code. But otherwise my bet would be to use triple slash paths `/// `. But I think you will complicate your setup and tooling unnecessarily by using .d.ts files directly in this way. – mweststrate Nov 21 '16 at 19:29
  • Using them in the way that they are designed to be used? If you have a .ts file with just interfaces in then you end up with an empty js file that is then needlessly loaded by the browser. – Roaders Nov 21 '16 at 20:03
  • bundling should prevent that? – mweststrate Nov 22 '16 at 06:19