I haven't published a npm package since a year but for a project I had to re-learn all the process and in parallel this is the occasion to write and share a minimalistic step by step tutorial to publish a npm package !
I assume you're already familliar with npm.
First step: project configuration
A npm package need a package.json file to be publish ! So let's create one.
npm init
I'm calling my project npmdemocreation.
We need that index.js file now where you're going to create a say hello function !
And we've done with the project config ! As mentionned earlier, let's keep things simple so we can focus on the most important: the process to publish a package.
Second step: Login to npm
If it is the first time we need to login with our credentials:
npm login
If you don't have a account, you can use their website to create your account or the command npm adduser
.
Third step: Publish!
According to npm, publishing a package is extremely simple, be curious and have a look here for more detailed explanations: npm official doc.
We have that publish command we can try:
npm publish
Well well well I personally got an error here and if we read a bit more carefully in the documentation it appears that we need to be explicit about the access option:
npm publish --access public
In fact, If you don't have a paid account, you can only use the public value.
At this point your log should confirm everything went allright!
I personally am able to search my package on npm and find it here !
Really simple isn't it ?
In case it's still not working verify that your package name doesn't already exist.
Fourth step: Try your package
Now open another folder and try your package!
For me it is:
npm install npmdemocreation
Then execute my sayHello function:
const sayHello = require('npmdemocreation');
sayHello();
We got that hello there!
Additional step: update your package
What if you want to modify your package and publish it again ?
Still easy npm publish
all the way!
Well not really, got an error ? Yes you can't ever publish with the same tag, if you look at the package.json version field, we're in 1.0.0.
You have to change this number in the package.json file or in the npm command with the --tag option.
You can't remove a version from npm once you published it, you always have to publish with a new version. However, you can provide a deprecation warning with the npm deprecate
command.
Things to keep in mind to publish a npm package:
- You need a npm account.
- Your package should contain a package.json file.
- All files in the package directory are included if no local
.gitignore
or.npmignore
file exist. - A given name and version combiaison can only be published once!
There are a lot of thing to explore but at least now you and me know how to publish a simple npm package.
Have a good day.
Top comments (0)