I'm making React component library. Project structure is something like:
src/
components/
utils/
hooks/
Now I'm trying to generate types (.d.ts.) files using rollup. Types are generated but e.g. my component NumberInput
is using absolute import from Input
component like so:
import Input from "components/Input/Input";
Now imports in NumberInput.d.ts
look exactly the same:
import Input from "components/Input/Input";
But now those imports in d.ts
files are not gonna be resolved since there is no tsconfig.json for generated code (I Guess).
tsconfig.json
{
"compilerOptions": {
"module": "esnext",
"target": "es5",
"lib": ["es6", "dom"],
"sourceMap": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src",
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"declaration": true,
"esModuleInterop": true,
"baseUrl": "src/",
"paths": {
"components/*": ["components/*"],
"models/*": ["hooks/*"],
"utils/*": ["utils/*"]
}
},
"exclude": ["node_modules", "build", "dist", "scripts", "acceptance-tests", "webpack", "jest"],
"types": ["typePatches"]
}
rollup.config.js
export default {
input: [
"./src/index.ts",
...getFiles("./src/components", extensions),
...getFiles("./src/hooks", extensions),
...getFiles("./src/utils", extensions)
],
output: [
{
dir: "dist",
format: "esm",
sourcemap: true
}
],
external: ["react", "react-dom", "styled-components"],
plugins: [
resolve(),
commonjs(),
typescript({
tsconfig: "./tsconfig.build.json",
declaration: true,
declarationDir: "dist"
}),
image(),
url({
include: ["**/*.woff2"],
limit: Infinity
}),
css(),
terser()
],
external: ["react", "react-dom", "styled-components"]
};
Is there any way I can control absolute imports when types are being generated? I wanna use absolute imports inside my project, but when types are generated I rly don't care how they look as long as they work.
The best working solution imo is nicely summed up in this article by using rollup-plugin-dts.
In plugin you can pass compilerOptions
parameter, with basePath
and paths
so it will correctly resolve absolute imports of type declarations.
rollup.config.ts
file:
...
plugins: [
dts({
compilerOptions: {
baseUrl: tsConfig.compilerOptions.baseUrl,
paths: tsConfig.compilerOptions.paths,
},
}),
],
...
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