Stav Alfi
Stav Alfi

Reputation: 13923

How to generate d.ts and d.ts.map files using webpack?

I can't find a way to generate d.ts and d.ts.map files using webpack. babel-loader only generates js and js.map files. I also need d.ts and d.ts.map files (which I was able to generate using tsc command) as shown in this picture:

enter image description here

Here is a minimal repo that contains all the settings: https://github.com/stavalfi/lerna-yarn-workspaces-example

More Details

I moved to Lerna + yarn. One of my packages is core (will be used in other packages) which is written in TS and JS.

I'm using webpack 4,babel-loader 8 for ts-to-js.

The other packages are trying to find type definitions and implementation of my core package but I was only able to generate index.js and index.js.map with webpack:

output: {
    path: distPath,
    filename: 'index.js',
  },
{
  "extends": "../tsconfig.settings.json",
  "compilerOptions": {
    "declaration": true,
    "declarationMap": true,
    "declarationDir": "dist",
    "rootDir": "src",
    "outDir": "dist"
  }
}

Does my strategy is wrong? what should I do?


I have tried a lot of plugins that generate d.ts files but they don't work and doesn't create d.ts.map files.

I already tried: typescript-declaration-webpack-plugin, npm-dts-webpack-plugin, dts-bundle-webpack, @ahrakio/witty-webpack-declaration-files. (They are listed in the package.json of core so you can clone and play with it).

Upvotes: 39

Views: 37900

Answers (2)

Stav Alfi
Stav Alfi

Reputation: 13923

Running ts-loader before babel-loader will do the trick.

Specifying that you want declaration files in config is all you need.


If you are using an absolute path, the output d.ts files will also contain absolute paths which are useless and will result in typescript compilation errors.

To fix that, I wrote a plugin to convert an absolute path to a relative path: https://github.com/stavalfi/babel-plugin-module-resolver-loader

Upvotes: 7

edwin
edwin

Reputation: 2821

You can call the Typescript compiler tsc directly to do that.

Use tsc --declaration to output a .d.ts file and tsc --declarationMap to generate the corresponding map file.

You can find more documentation here: https://www.typescriptlang.org/docs/handbook/compiler-options.html

Upvotes: 3

Related Questions