This is a continuation of my previous guide. Refer it to learn how to publish code to npm
This article focuses on publishing code for use in a browser.
There will be 2 sections to this guide :
For both cases, we will eventually deploy the code to npm to leverage the power of the free CDN unpkg
This one is easier. As the code is already in browser-usable format, it just needs to be included in the HTML code via the <script>
tags.
This will make its variables and functions available to the browser automatically.
To publish it to a CDN :
npm init -y
to initialize a package.json
for the repository.unpkg.com/repository-name
according to the repository name provided by you while publishing to npm
. This is the CDN auto-generated from npm.<script>
tags. If you get a file directory structure, simply navigate to the desired file and include it in your frontend via <script>
tags.Browserify bundles all the dependencies of your js file into a single file, and exports a variable to window
for use within the browser.
npm add browserify -g
.browserify ./main.js -o ./bundle.js -s variableName
Here, main.js
is the file you want to use in browser,
-o
flag is used to define the location of the output file, and
-s
flag is used to define the variable name exported to the browser
unpkg.com/repository-name
to access the CDN generated for your repo.<script>
tags. If you get a file directory structure, simply navigate to the desired file and include it in your frontend via <script>
tags.That’s it, you successfully published your JS library 🎉 !
Pat yourself on the back, you earned it 😁 !
Get in touch !!