Sometime you might be feeling lazy or quickly want to test out some features or functionality using the NPM package directly inside the browser. To run any package in the browser you need UMD (Universal Module Definition) build of that package. In the following example from React(a popular JavaScript library for building user interfaces), we can see umd
folder included in the released version i.e. 16.7.0
.
UMD modules are capable of working everywhere, be it in the client, on the server, or elsewhere.
UNPKG is a fast, global content delivery network for everything on npm. Use it to quickly and easily load any file from any package using a URL like:
https://unpkg.com/:package@:version/
where,
package
is the name of npm packageversion
is a version of the package. If you omit the version from URL, unpkg will automatically pick the latest version of underlying packageThe above URL can be loaded similar to any other javascript file using script tags as follows
<script crossorigin src="https://unpkg.com/:package@:version/"></script>
To load an entire package we need to directly specify the package name followed by URL https://unpkg.com/
. Following is the example of React npm package
https://unpkg.com/react/
By default unkpg will automatically redirect above URL to latest version of package. To load specific version, we can specify the version after package name separated by @. For example:
https://unpkg.com/react@16.7.0/
You may also use a semver range or a tag instead of a fixed version number, or omit the version/tag entirely to use the latest tag.
Loading single file is very much similar to any package. We need to append the file name in unkpg URL as follows
https://unpkg.com/:package@:version/:file
https://unpkg.com/react@16.7.0/package.json
Once the package is included in webpage using script tag, the global variables exposed by package can be directly invoked inside <script>
tags to perform certain operations.
Let’s understand this with following example where we are including the React
and ReactDOM
packages.
Once the package is loaded we can call ReactDOM.render()
method to dynamically inject element in a DOM node that is having id
of root
<html> <head> <title>Load NPM package in browser</title> <script crossorigin src='https://unpkg.com/react@16/umd/react.production.min.js' ></script> <script crossorigin src='https://unpkg.com/react-dom@16/umd/react-dom.production.min.js' ></script> </head> <body> <div id='root'></div> <script> ReactDOM.render(React.createElement("h1", null, "Dynamic tag created by React"), document.querySelector("#root")) </script> </body> </html>