简体   繁体   中英

How to create npm package with definition files?

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 )

There are two methods to publish definiton files:

  1. bundling with your npm package,
  2. or publishing to the @types organization on npm.

Here is the documentation to help you with that

To bundle the types with your package, there are two specific things for you to do:

  1. Set "declaration" in tsconfig.json . This tells TypeScript to generate *.d.ts files.
  2. Set "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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM