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:
Here is a minimal repo that contains all the settings: https://github.com/stavalfi/lerna-yarn-workspaces-example
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" } }
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 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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With