I'm working on a few TS packages with the following setup and am getting TS7016 errors.
Module A (to-be-imported)
// package.json
"name": 'module-a'
...
"main": "./dist/index.js",
"types": "./dist/types/index.d.ts",
...
// tsconfig.json
{
"compilerOptions": {
"module": "CommonJS",
"target": "ES2018",
"lib": ["es2016", "es2017.object", "es2017.string"],
"declaration": true,
"outDir": "./dist",
"declarationDir": "./dist/types",
"sourceMap": true,
"declarationMap": true,
"resolveJsonModule": true,
"esModuleInterop": true
},
"include": ["src"]
}
Module B (trying to import module A)
import { TypeA, TypeB, ... } from 'module-a' <- results in TS7016 error
Module B's TSConfig
{
"extends": "@tsconfig/node18",
"compilerOptions": {
"outDir": "./dist",
"inlineSourceMap": true,
"inlineSources": true,
"experimentalDecorators": true,
"rootDir": "."
},
"exclude": ["build", "node_modules", "dist"]
}
I believe the typescript is looking for the types in the root module instead of looking for it in the nested /types/ subdirectory
To resolve this, I've noticed 2 changes worked and I'm trying to understand why.
Option 1 - Change moduleResolution to node in ModuleB
Requires changing module to commonjs since the default extend is using node16
{
"extends": "@tsconfig/node18",
"compilerOptions": {
"outDir": "./dist",
"inlineSourceMap": true,
"inlineSources": true,
"experimentalDecorators": true,
"rootDir": ".",
"moduleResolution": "node", // NEW
"module": "commonjs" // NEW
},
"exclude": ["build", "node_modules", "dist"]
}
Option 2 - Changing the types to be output in the module-a's main dir
// updated module-a tsconfig
{
"compilerOptions": {
"module": "CommonJS",
"target": "ES2018",
"lib": ["es2016", "es2017.object", "es2017.string"],
"declaration": true,
"outDir": "./dist",
"declarationDir": "./dist", // <-- UPDATED
"sourceMap": true,
"declarationMap": true,
"resolveJsonModule": true,
"esModuleInterop": true
},
"include": ["src"]
}
Both work, but I'm wondering if there's a benefit to keeping the declaration nested in the /types/ folder, or if it should just be in the root dir? TS documentation shows it in the main dir. https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html
Any context and information is appreciated. I'm still trying to learn about package.jsons and how these things come together.
package.json. A package can be made up of many modules.