Assuming that you already have npm
installed, then creating and publishing a new npm package is really easy and fast. Keep in mind that these are the minimum recommended steps, and I'll provide more resources at the bottom for more configuration options and deeper dives.
The first section show how to publish the npm package, then the second section shows how to use it in another JavaScript project.
How to Publish
(Recommended, optional) Create a new remote git repo with a README.md file
- The benefit of having the remote repo already setup is to allow the npm setup to be smarter, filling out more git-related fields automatically.
Create a local project directory:
- If you have the remote repo, then run:
git clone <my-repo-url>
- If you don't want a remote repo, then run:
mkdir <my-project-name>
- If you have the remote repo, then run:
Setup the npm project:
- Run:
cd <my-project-name> && npm init
- Follow the interactive steps until the package.json file is created. At least add a name and email.
- Run:
Create 'index.js' and add the following content as an example:
const utils = { isOdd (num) { return num % 2 === 1 }, sayHello () { console.log('Hello, World!') } } module.exports = utils
Create '.gitignore' and add the following content ('npm pack' in the next step uses this file):
*.tgz .idea/ node_modules/
(Optional) Ensure that the correct files will be uploaded for the npm package:
- Run:
npm pack
- Check the output of the 'Tarball Contents' sections
- Run:
Publish your new npm package: :)
- Run:
npm publish
- Ensure that there is no error. If you have a package name that is already taken, then there will be an error and you'll have to update the 'name' in 'package.json'
- Run:
(Optional) To see your package in the npm registry, run:
npm home <my-package-name>
How to Use
(Optional) Create a new npm project:
- Run:
mkdir <my-new-project-name> && cd <my-new-project-name> && npm init -y
- Note: The
-y
means accept all the default values
- Note: The
- Run:
In your new project, install your new npm package (use the package name from the above section)
- Run:
npm install --save <my-npm-package-name>
- Sidenote: An equivalent command is 'npm i -S
'
- Sidenote: An equivalent command is 'npm i -S
- Run:
Create 'index.js' and add the following content as an example (and replace
below): const utils = require('<my-npm-package-name>') utils.sayHello() console.log(utils.idOdd(1)) console.log(utils.idOdd(2))
Run your project:
node index.js
// Output Hello, World! true false
Congrats on creating your new npm package! :)
Helpful Resources
- Great: https://zellwk.com/blog/publish-to-npm/
- Great: https://webpack.js.org/guides/author-libraries/
- Great: https://itnext.io/step-by-step-building-and-publishing-an-npm-typescript-package-44fe7164964c
- Includes great additions for automating the build and publish process