Reputation:
How to create an NPM package with definition files where declared only interfaces in *.ts
files.
Let's suppose we have two interfaces and one class defination:
export interface A {
id: number;
}
export interface B {
name: string;
}
export class C {
}
I need to pack these *.ts
files in package npm, how to do that? Should I export them in index.ts
?
My package.json
is:
{
"name": "npm",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
My tsconfig.json
is:
"compilerOptions": {
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
}
Inside index.ts
there is:
import { A } from "./a";
import { B } from "./b";
import { C } from "./c";
Where './a', './b', './c'
is files with declarations of interfaces and classes.
When I build it to index.js
file using command: tsc index.ts
then I can not get access to interfaces using module index.js
in others projects (npm install )
Upvotes: 8
Views: 1472
Reputation: 141512
To bundle the types with your package, there are two specific things for you to do:
"declaration"
to true
in tsconfig.json
. This tells TypeScript to generate *.d.ts
files."types"
in package.json
. This tells TypeScript where to find generated *.d.ts
files.tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"declaration": true <----------------------
}
}
package.json
{
"name": "my-package",
"version": "1.0.0",
"main": "index.js",
"types": "index.d.ts", <----------------------
"license": "ISC",
"devDependencies": {
"typescript": "^3.8.3"
}
}
Here is a working example for you on GitHub. All of the above and more details are hidden in the documentation.
Upvotes: 4
Reputation: 713
There are two methods to publish definiton files:
Here is the documentation to help you with that
Upvotes: 1