[英]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和nodejs后,可以通过运行轻松使用模块
npm install module npm安装模块
and then using the js require() function. 然后使用js require()函数。 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 ? 但是,如果我想在客户端的浏览器中使用此模块的javascript函数怎么办? 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. 经过一些工作,我可能最终可以在磁盘或Web上找到一些文件,并在其中找到所需的源代码。 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: 如果该库是作为标准javascript模块发布的,则可以将其直接加载到浏览器中,如以下示例所示:
<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: unpkg服务提供了一个有用的工具,可以自动将模块说明符转换为绝对URL,您只需添加?module
查询字符串即可:
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. 但是,如果(不幸的是通常)情况是该库以CJS模块发布,则需要使用模块捆绑器。 I'm partial to rollup . 我偏爱汇总 。 To roll cjs modules up in your bundle, make sure to install and use the rollup-plugin-commonjs plugin. 要在包中汇总 cjs模块,请确保安装并使用rollup-plugin-commonjs插件。
There are a variety of tools available to merge your dependencies into a single file that can be consumed by a web browser. 有多种工具可用于将依赖项合并到一个文件中,以供Web浏览器使用。 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. 该列表并不意味着要全面,甚至不建议使用哪种工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.