Building and publishing an NPM package involves a series of steps. Here is a detailed process:
Pre-Requisites:
You need to have Node.js and npm installed on your computer. You can check whether you have Node.js installed by running the command “node -v” and for npm “npm -v”. If not, download and install them from the official website.
Steps to create, build and publish an NPM package:
1. Create a Directory: Create a new directory for your package and navigate into it using your terminal.
\`\`\`bash mkdir my-package cd my-package \`\`\`1. Initialize Your Package: Run “npm init”. This will prompt you to enter some information about your package like name, version, description etc. You can also run “npm init -y” to skip the questionnaire and create a default package.json file.
\`\`\`bash npm init -y \`\`\`1. Write Your Code: Create a new file (index.js, or whatever you named your main file in package.json) and start writing your package’s code.
\`\`\`bash touch index.js \`\`\`1. Create a README File: It’s a good practice to create a README file and write all the necessary details about your package like how to install, how to use, contributions etc.
\`\`\`bash touch README.md \`\`\`1. Create a .gitignore file: Create a .gitignore file and add node\_modules in it to prevent uploading of dependencies.
\`\`\`bash touch .gitignore echo “node\_modules” > .gitignore \`\`\`1. Create an NPM Account: To publish your package, you need an npm account. You can create it by visiting the npmjs website or through the command line using “npm adduser”. If you already have an account, you can login using “npm login”.
\`\`\`bash npm adduser or npm login \`\`\`1. Publish Your Package: You can finally publish your package using “npm publish”. Make sure to update the version in package.json each time you publish.
\`\`\`bash npm publish \`\`\`Note: If it’s a scoped package (like @username/package), you need to mention —access public while publishing the first time.
\`\`\`bash npm publish —access public \`\`\`1. Test Your Package: Now, you can test your package by installing it in another project using “npm install your-package-name”.
That’s it. You’ve published your npm package.