Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"   } } 
  • When I compile with tsc (without webpack), everything is working great as I showed in the picture above.

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).

like image 575
Stav Alfi Avatar asked Mar 23 '19 21:03

Stav Alfi


People also ask

Does TSC use webpack?

Like Babel, Webpack depends on TSC to transpile TypeScript to JavaScript but as TSC doesn't have a clue about Webpack, hence Webpack needs a loader to talk to TSC. This is where the ts-loader comes into play. Webpack compiles a TypeScript file using ts-loader package which asks TSC to do the compilation.

Is it possible to generate TypeScript declaration files from JS library?

JavaScript doesn't always contain enough type information for the TypeScript compiler to infer the structures in your code - so automatically generating a definition based on JavaScript is rarely an option. But there is one trick that might work (it only works in a limited set of cases).


1 Answers

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

like image 85
Stav Alfi Avatar answered Sep 21 '22 22:09

Stav Alfi