简体   繁体   English

如何使用browserify在客户端html文档中使用Node.js包

[英]How to use Node.js packages within a client-side html document using browserify

I'm unable to use a node.js module on my website with broweserify. 我无法通过broweserify在我的网站上使用node.js模块。 The example only shows how to run a javascript file that is separate from the .html file, not how to use the node.js module within the .html file. 这个例子只能说明如何运行的JavaScript文件是从.html文件分开,而不是如何使用Node.js的模块.html文件 Seems like a trivial problem, but I'm unable to make it work. 似乎是一个小问题,但我无法使其正常工作。

Here's what I've done: 这是我所做的:

  1. Initialized node.js & installed a package, npm i webtorrent-health as an example 初始化node.js并安装了一个软件包,以npm i webtorrent-health为例
  2. Created require_stuff.js which consists of a single line: var WebtorrentHealth = require('webtorrent-health') 创建了由一行组成的require_stuff.jsvar WebtorrentHealth = require('webtorrent-health')
  3. Run browserify: browserify require_stuff.js > bundle.js 运行browserify require_stuff.js > bundle.jsbrowserify require_stuff.js > bundle.js
  4. Include package in my html document, eg <script src='bundle.js'></script> 在我的html文档中包含包,例如<script src='bundle.js'></script>
  5. Use the package somewhere in my document, eg like this: <script>webtorrentHealth(magnet).then(foobazbar())</script> 在我的文档中的某处使用该软件包,例如: <script>webtorrentHealth(magnet).then(foobazbar())</script>

Despite bundle.js executing and seemingly defining webtorrentHealth, the script within the .html document fails with WebtorrentHealth is not defined . 尽管bundle.js执行并似乎在定义webtorrentHealth,但是.html文档中的脚本失败,并且WebtorrentHealth is not defined What am I doing wrong? 我究竟做错了什么? How do I make it work? 我该如何运作? Thank you! 谢谢!

You're very close to what you want to achieve. 您非常接近要实现的目标。 In fact, your code bundle.js is inaccessible from outside (in your case the browser) due to browserify, but you can expose your module by writing at the end of your file require_stuff.js: 实际上,由于browserify的原因,无法从外部(在您的情况下为浏览器)访问您的代码bundle.js,但是您可以通过在文件require_stuff.js的末尾编写来公开模块:

window.WebtorrentHealth = WebtorrentHealth; window.WebtorrentHealth = WebtorrentHealth;

Now you can use WebtorrentHealth in your document. 现在,您可以在文档中使用WebtorrentHealth。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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