Publishing a package is pretty straightforward and not time-consuming. Moreover, it's an excellent option to make your code reusable and available for many of your projects.
First, you have to create an account on npmjs website.
Before we start doing all the necessary for publishing the package, it's better to prepare your repository in advance.
I'll create a repository on GitHub. Create repository with name
Here is how looks my repository configuration.
Let's clone it and go inside the folder:
git clone https://github.com/obaranovskyi/math-library-add && cd math-library-add
Add
In our case, it looks pretty simple:
node_modules
Init npm inside of the project:
npm init --yes
You accept all defaults when you're using
Install
npm install -D typescript
Init typescript:
npx tsc --init
This command creates the default
- We need to uncomment
declaration ,declarationMap , andsourceMap . - Include
src folder, by addinginclude property with value["src"] - Add
outDir with the name of the folder where we want to keep our compiled javascript files. I'll name my folderlibrary .
Your configuration should like this:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"outDir": "library"
},
"include": [
"src"
],
}
Let's add the code we want to publish and reuse later on.
Create folder
I'll put something simple inside.
export function add(x: number, y: number): number {
return x + y;
}
- Update your
package.json file:- We need to update
main property tolibrary/index.ts . So others can determine the main file in the project. types has to be set tolibrary . Here we're pointing to the folder where we keep the types.- To
scripts we need to addbuild script, it looks like thistsc -p . - Update
keywords . In my case, I'll addmath ,add ,library ,typescript . - Update
author , put your name there. - Add
repository with value{ "type": "git", "url": "https://github.com/obaranovskyi/math-library-add.git" } , - Add some
description . - In addition, you can update the
license . We can useMIT .
- We need to update
Your
{
"name": "math-library-add",
"version": "1.0.0",
"description": "",
"main": "library/index.ts",
"types": "library",
"scripts": {
"build": "tsc -p ."
},
"keywords": [
"math",
"add",
"library",
"typescript"
],
"author": "Oleh Baranovskyi",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/obaranovskyi/math-library-add.git"
},
"description": "This is just a test library.",
"devDependencies": {
"typescript": "^5.0.4"
}
}
First, we need to build the project.
npm run build
The project was compiled into
We're ready to publish our package:
npm publish --access public
Now the we need to commit and push our changes to GitHub.
git add .
git commit -a -m "Library base."
git push