我正在尝试使用 JS 模块制作简单的页面,该模块将对页面执行某些操作。我需要使用 node.js 的模块,所以我正在学习如何浏览器化工作。
我的 HTML:
<!doctype html>
<html>
<head>
<script src="js/bundle.js" type="text/javascript"></script>
</head>
<body>
<p>Hello world!</p>
<script type="text/javascript">
var test = require("./test.js");
test.init();
</script>
</body>
</html>
这是我的 JavaScript (test.js):
"use strict";
alert("here1");
var init = function() {
alert("here2");
}
exports.init = init
我正在捆绑:
browserify.cmd test.js -o bundle.js
当我尝试打开页面时,它显示“here1”,但不显示“here2”。 在浏览器的控制台中我看到:
Uncaught ReferenceError: require is not defined index.html:9
有什么想法可以让模块的函数(init)正常工作吗?
您需要将包含 Node 中任何内容的所有 JavaScript 代码放入
test.js
文件中,然后使用 browserify 将其转换为 te bundle.js
。在您的示例中,您在 require
中使用节点函数 index.html
,该函数不会被转换。然后浏览器会看到他不知道的函数 require()
,这就是问题隐藏的地方。
简单来说:您的所有 javascript 代码(包含 Node)必须作为单个
index.html
包含在您的 bundle.js
中,这是来自源文件的浏览器结果。
编辑
Browserify(默认情况下)不允许您从浏览器化代码中调用任何浏览器化函数。但是您可以通过将函数附加到
window
范围来使其可用。
这是
test.js
(然后通过 browserify转换为
bundle.js
)和 index.html
"use strict";
alert("here1");
window.init = function() {
alert("here2");
}
<!doctype html>
<html>
<head>
<script src="js/bundle.js" type="text/javascript"></script>
</head>
<body>
<p>Hello world!</p>
<script type="text/javascript">
init();
</script>
</body>
</html>
这是“浏览器无法访问”的热门搜索,我只是浪费了至少几个小时自己没有得到它。也许其他帖子、博客和教程都很迟钝,或者也许只是我,但这是一个我希望有人向我展示的例子:
const trie = require('trie') <---you want to use this module like in node
运行此命令(安装 browserify 后):
browserify -r trie -s trie > trie.browser.js (if node can find it, browserify should)
-r = --require [模块名称]
-s = --standalone [浏览器 JS 环境中模块的全局范围(!) var 名称]
(您还可以使用 -o 作为 --output 选项,而不是使用 > 进行重定向)
然后在浏览器代码中您可以执行以下操作:
const LexTrie = new trie.Trie()
...or...
const LexTrie = trie.createTrieFromJson(lexicon_trie_json)
这比使用 require 制作一个中间文本文件要好,这对我来说无法将模块置于全局范围,直到我做了类似的事情:
window.trie = require('trie')
...此时它起作用了,但我知道必须有一种更简单的方法。
希望这对像我这样的人在未来因为没有突出显示 --standalone 选项而无法获得 browserify 文档时有所帮助....