我正在使用 Browserify 从 index.html 文件(托管在 Google App Engine 上)访问 Node 模块
我将模块导入到“main.js”文件中,正如我在 Browserify 文档中看到的标准,如下所示:
var request = require('request');
var fs = require('fs');
然后我使用以下命令将其捆绑到一个bundle.js 文件中:
browserify main.js -o bundle.js
这成功地生成了所需的bundle.js 文件。然后我将其包含在我的 index.html header 顶部,如下所示:
<HEAD>
<script src="/scripts/bundle.js"></script>
<script src="/scripts/util/loader.js"></script>
<!-- More scripts below here -->
然后,index.html 主体中的脚本调用 loader.js 中使用该行的函数
request('api.my-url.com/world').pipe(fs.createWriteStream('/resources/myMap.json'));
我用它来尝试创建一个包含响应内容的文件。然而,当我在 GAE 上部署它并访问 index.html 时,我收到了错误消息:
loader.js:15 Uncaught ReferenceError: request is not defined
at loadWorld (loader.js:15)
at Object.create ((index):55)
如果我尝试将 request() 调用移至 index.html 中的脚本中,我会遇到同样的问题,但如果我将该行移至 main.js 中,我就不再遇到此问题。
我认为这是个人对Javascript的误解,但我似乎无法弄清楚为什么在bundle.js通过脚本标签包含在index.html中之后,请求对象在index.html中不可用.
非常感谢任何能够阐明情况的人,谢谢。
最佳答案
当您创建 browserify bundle 时,它旨在成为应用程序的“入口点”。但似乎在这里你在index.html中有你的入口点,所以你想要的是捆绑一个独立的库。
Browserify 有一个名为 --standalone
的选项为此,它会生成 UMD bundle :https://github.com/substack/browserify-handbook#standalone
您可以以大致相同的方式调用它,但指定应为 UMD 包指定什么名称(在全局命名空间中)。例如。
browserify foo.js --standalone mylib > bundle.js
现在当你包含 <script src="bundle.js"></script>
时在您的 html 中,后续脚本将能够引用 mylib
对象。
这是使用 --standalone
的示例选项:
- https://github.com/joshwnj/react-visibility-sensor/tree/master/example-umd
- https://github.com/joshwnj/react-visibility-sensor/blob/master/package.json#L9
此外,如果您想要类似 request
的内容可以在浏览器中使用,https://www.npmjs.com/package/xhr有一个非常相似的 API。
关于javascript - 包含bundle.js脚本后,无法从index.html引用Browserify模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41451345/