May 15, 2019
Recently, I thought it would be a good idea to modularise some of my JavaScript code into reusable npm
packages. It started out as something very trivial, but I had to spend considerable amount of time into setting everything and get it working. This article is an attempt to summarize the learning, and create something useful.
To make things simpler and to reduce boilerplate code generation, I have created and published a CLI tool. The tool can be found on npm repository, and the source code for it can be found on GitHub. We will be using this CLI to generate the boilerplate code for npm package. Please watch the below video to see it in action, and follow below instructions to give it a spin.
One needs an NPM account to be able to publish the packages on npm registry. Head to https://www.npmjs.com/ and create an account. After creating the account, you need to run npm login
in the terminal using the credentials you used to create the account on NpmJs. Publishing public packages is free on NpmJs. However, if you wish to publish private packages, you need a paid account.
create-npm-package
CLI tool ⚒️npm install -g @a6kme/create-npm-package
Once you have come up with a name for your package, create the boilerplate for that package with command create-npm-package <YOUR_PACKAGE_NAME>
src/
of the project directory.<script>
tag in HTML files, select this option. The reason for asking this is the type of bundle webpack will output. If it needs to be used as part of a HTML document, the format has to be UMD. Else, commonJS2 will be more appropriate. You can read more about it in webpack official documentation of output.libraryTarget.The moment that you have been waiting for. You can publish your package now.
npm publish --access public
You can checkout your published package on npmjs.com under your profile. The link should look like https://www.npmjs.com/settings/<YOUR_NPM_USERNAME>/packages
. You can install this package as a dependency in other project, or can use it as a script tag in browser.
unpkg.com provides free CDN for your published packages on npm. You can access your build by going to unpkg.com/@<YOUR_NPM_USERNAME>/<YOUR_PACKAGE_NAME>
and then using the distribution as <script>
tag in an html file.
_ _ _ _
Thank you so much for taking time to go through this.❤️ If you feel there is some typo in this article, or some of the content can be improved, please feel free to Edit this Post. Or you can go back to continue reading other articles. 😀