HomeTutorsContact
Browser
How to load any npm module in browser?
Gulshan Saini
July 22, 2020
1 min

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.

unkpg umd folder
unkpg umd folder

Let’s see how we can include any npm package or file in browser

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:

where,

  • package is the name of npm package
  • version is a version of the package. If you omit the version from URL, unpkg will automatically pick the latest version of underlying package

The above URL can be loaded similar to any other javascript file using script tags as follows

Loading entire NPM package

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

example

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:

example

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 from NPM package

Loading single file is very much similar to any package. We need to append the file name in unkpg URL as follows

example

How to use UMD package in browser?

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

Output


Tags

#tips
Previous Article
How to set dynamic inner text with React.createElement()?

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

How to launch Chrome browser from command line?
September 10, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media