I have a typescript application which I want to bundle with rollup including all typescript declaration files. Therefore I am using @rollup/plugin-typescript
and I also set the option declaration
to true
in tsconfig.json
. Since I need some values from package.json
, I have to import that file in my scripts. So basically my index.ts
looks like this:
import packageJson from '../package.json'
export const foobar = () => {
return packageJson.name
}
And my rollup-config.js
looks like this:
import typescript from '@rollup/plugin-typescript'
import json from '@rollup/plugin-json'
export default {
input: 'src/index.ts',
output: {
file: './dist/index.esm.js',
format: 'es',
},
plugins: [
json(),
typescript()
]
}
The problem is that the file index.d.ts
for typescript declarations is not automatically generated by the rollup plugin. If I remove the import of package.json
everythings works fine. So in general, if I import json files, the option declaration: true
is ignored. What can I do to generate those typings?
For the sake of completeness here is also my tsconfig.json
:
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"useDefineForClassFields": true,
"sourceMap": true,
"baseUrl": ".",
"resolveJsonModule": true,
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
],
"declaration": true,
"declarationDir": "dist/types"
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
],
"exclude": [
"node_modules"
]
}
OK, I guess I figured it out. Turns out the problem is that the package.json
is located outside my src
dir and therefore ignored by the bundler.
I followed the instructions in this post and modified my rollup config. Afterwards the declaration files were generated correctly.
import typescript from '@rollup/plugin-typescript'
import json from '@rollup/plugin-json'
export default {
input: 'src/index.ts',
output: {
file: './dist/index.esm.js',
format: 'es',
},
plugins: [
json(),
typescript({
tsconfig: 'src/tsconfig.json' // this line was added
})
]
}