It is a usual practice in huge organisations to group common parts of a project and to modularize it for re-usability within the organisation. In Node JS, Packages are the way to go for organizing the parts of gigantic projects and modularizing it’s code.
Following are the steps on how you can create your own NPM Package/Node Package/TypeScript Package :
1. Package.json File
Make sure a package.json file exists for the project that you wish to package. If there is no package.json file, you can create one by running the command
npm init in your project directory.
2. Install tslib
Install tslib which is an npm package that helps in resolving the imports consisting of aliases. It can be installed by running the command
npm i tslib in your project directory.
3. Tsconfig.json File
Make a tsconfig.json file referring the following structure –
Some of the important things to note in tsconfig.json file —
Is used to make type declaration files <filename>.d.ts when building the package.
For Eg : index.d.ts
Specifies the build output directory.
Since we are using tslib this will help while using the package by importing it!
– BaseURL and paths
@packname is an Alias for the root folder of the package
4. The final package.json looks something like this –
Some of the important things to note in package.json —–
All the typescript packages require declaration files and
“types” specifies the index declaration files, note that these files are made during compilation only when you set the declaration flag in tsconfig as true.
_moduleAliases as mentioned in the above section-
“files” : ["build/**/*"]
This specifies the files/folders to be included when you package your project.Only the compiled files residing inside the build folder are required. Using
"build/**/*" thus includes only the build files.
5. Instructions to auto-generate the index file
- Install a node package called ‘create-ts-index’ locally as a developer dependency
npm install create-ts-index --save-dev
or globally as
npm install create-ts-index –g
- Run the following command in the root folder of your project
cti entrypoint -n ./
This will create a file with the name “entrypoint.ts” containing exports of all the files in your project. Rename it to index.ts
Finally to create the package compile your project first by running
7. Pack or Publish
If the project compilation succeeds without any errors make the package by running
npm pack generates a .tgz file which can then be shared and installed by
npm i in another projects or publish it by running