Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
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 :
- Publishing browser-native code 🌐
- Converting an npm module for use in a browser 🔃
For both cases, we will eventually deploy the code to npm to leverage the power of the free CDN unpkg
1. Publishing browser-native code 🌐
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 :
- Use npm init -y to initialize a package.json for the repository.
- Publish it to npm via the steps given here : Steps to Publish
- Navigate to unpkg.com/repository-name according to the repository name provided by you while publishing to npm. This is the CDN auto-generated from npm.
- If you get your desired file, you can use it in the browser via <script> tags. If you get a file directory structure, simply navigate to the desired file and include it in your frontend via <script> tags.
- Access your variables and functions directly by name
2. Converting an npm module for use in a browser 🔃
Browserify bundles all the dependencies of your js file into a single file, and exports a variable to window for use within the browser.
- Install Browserify npm add browserify -g.
- To generate your browser usable file, do
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
- Publish to npm including your bundled JS file. Navigate to unpkg.com/repository-name to access the CDN generated for your repo.
- If you get your desired file, you can use it in the browser via <script> tags. If you get a file directory structure, simply navigate to the desired file and include it in your frontend via <script> tags.
- Access your code via the variable name that you exported.
That’s it, you successfully published your JS library 🎉 !
Pat yourself on the back, you earned it 😁 !
Get in touch !!
Publishing a JavaScript Library Online: The Definitive Guide was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.