3

一日一技:如何在浏览器中使用npm包?

 2 years ago
source link: https://www.kingname.info/2022/03/06/use-npm-package-in-browser/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一日一技:如何在浏览器中使用npm包?

发表于

2022-03-06

| 分类于 JavaScript

| 评论数: 0

我们知道,Python的第三方库一般可以使用pip来安装。如果代码比较简单,我们甚至可以把第三方库的代码复制下来,放到项目里面导入。

但由于JavaScript生态里面,有Node.js这个东西,这就导致第三方库有两种不同的导入方式。如果我们要做一个网站,我们通常会在HTML中,使用<script>标签引入.js文件,例如:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>

这样导入了.js文件以后,里面的代码在网页加载完成后就会运行。

但在Node.js生态里面,第三方包一般需要使用npm安装,然后在代码里面通过require导入。最后再用webpack打包编译成能直接在浏览器中运行的JavaScript代码。

如果我找到一个第三方的包,它只提供了npm版本,没有提供直接在浏览器中导入的版本怎么办?

举个例子,我想把CSS Selector转换成XPath。在Github上面,可以搜索到很多这种第三方包,例如:featurist/css-to-xpath: Convert CSS selectors to XPaths, in JavaScript 或者sergeidyga/cssxpath

但你会发现,这些包都只提供npm安装的版本,没有办法直接在浏览器中通过


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK