简体   繁体   中英

What is the proper way to to serve javascript sources of npm modules on a browser?

Once npm and nodejs installed, it is possible to easily use a module by running

npm install module

and then using the js require() function. I assume the source code stored somewhere on my computer will then be loaded. But what if I want to use javascript functions of this module within a client's browser ? With a bit of work, I can probably end up finding some file on my disk, or maybe on the web, with the source code I need inside it. My question is : is there a standard process that gathers all the dependencies of a given module, so I can serve them on a client website ? Or do I totally miss something and things are suppose to be done in an entirely different way ?

If the library is published as standard javascript modules, you can load it directly into the browser, as in this example:

<script type="module">
  import { html, render } from '/node_modules/lit-html/lit-html.js';
  render(html`<span>Hello, world</span>, document.body)
</script>

The unpkg service provides a useful tool to automatically transform module specifiers to absolute URLs, you just have to add the ?module query string:

import { html, render } from 'https://unpkg.com/lit-html/lit-html.js?module';

If, however, as is (unfortunately commonly) the case, the library is published as CJS modules, you'll need to use a module bundler. I'm partial to rollup . To roll cjs modules up in your bundle, make sure to install and use the rollup-plugin-commonjs plugin.

There are a variety of tools available to merge your dependencies into a single file that can be consumed by a web browser. Such tools are typically referred to as "bundlers".

A few popular examples include:

This list is not meant to be comprehensive or even a recommendation of which tool to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM