Ambient Typescript Definitions Not Bundled in Library

343 Views Asked by At

I'm working with the TSDX tool to build a react-typescript library. I have a number of types exported in my @types/ directory which are clearly picked up by the compiler as I use them within the app with no trouble.

However, during my build, they do not get copied into my output bundle, which surprises me, since they are referenced through the code (which does get bundled correctly).

// tsconfig.json
{
  "include": ["src", "types", "test"],
  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "lib": ["dom", "esnext"],
    "importHelpers": true,
    "declaration": true,
    "sourceMap": true,
    "rootDir": "./",
    "strict": true,
    "noImplicitAny": false,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": false,
    "noFallthroughCasesInSwitch": true,
    "moduleResolution": "node",
    "baseUrl": "./",
    "paths": {
      "*": ["src/*", "node_modules/*"]
    },
    "jsx": "react",
    "esModuleInterop": true
  }
}
1

There are 1 best solutions below

0
On BEST ANSWER

This is actually, believe it or not, by design.

You can define the location of your types in tsconfig.json and it is expected that they are always in the final build (by the fact that they are not moved). i.e. given this structure:

src/app.ts
types/app.d.ts

Typescript would expect your published build to be something like:

build/app.js
build/app.d.ts
types/app.d.ts

To achieve this you would either define a path to your ambient types within tsconfig

{
    baseUrl: "./",
    paths: [
        "my-app": "./types/app.d.ts"
    ]
}

or add a typeRoot that would include all types within a directory, careful with this, it will override any existing typeRoots such as those to node_modules/@types so you need to redeclare them.

{
    typeRoots: ['./types', 'node_modules/@types']
}

and then consume the types using an import of my-app if you've declared a path.

It would be expected that your final build would include the types directory in the root where it was defined in your tsconfig.json.

I suspect that you are including your .d.ts file within your applications source directory, and as such not expecting it to ever make it to a production build. In this case you would need to manually move it to the location that it is needed in your build or automate it with some other plugin depending on your build tooling.