I am writing a NPM package with TypeScript but I could not find a way to convert Webpack alias in TypeScript Declaration.
webpack.config.js
{
// ...more Webpack configurations
resolve: {
extensions: [".ts", ".js"],
alias: {
"@": resolvePath("src")
}
}
tsconfig.json
{
"compilerOptions": {
// More options
"paths": {
"@/*": ["src/*"]
}
}
}
I am using babel-loader
with @babel/preset-typescript
but it does not output declaration files.
tsc --emitDeclarationOnly
emits declaration files but it does not replace @/
with correct path. Same for ts-loader
.
I am able to get it working in Jest with moduleNameMapper
. If I can get it working building declaration files, I not longer need to write somethings like ../../../../model
.
Most of the answers I found online is about compiling JavaScript files, which I don't have a problem with. Any help will be appreciated.
For Webpack, we need webpack and webpack-cli package and for TypeScript features, we need typescript and ts-loader packages. Now that all the dependencies are ready to be used, we need to create the webpack.
Aliases are a way to let webpack know where to find our code by providing a word or character that represents a partial reference to where the code is located. Once webpack knows this, the code can be properly resolved while it is compiling during development or building the final package.
I finally find a solution. You need ttypescript
and typescript-transform-paths
. You add the following to compilerOptions
in tsconfig.json
"plugins": [
{ "transform": "typescript-transform-paths", "afterDeclarations": true }
]
and run
ttsc --emitDeclarationOnly
I wrote an article on this.
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