有人熟悉Yabble吗?或者其他浏览器端的 CommonJS 加载器?
我正在尝试使用 Node.js,并且非常想创建可以在服务器端和客户端互换使用的 Javascript 模块。这最终可能更像是一种“因为它很棒”的东西,而不是“因为它实用和有用”的东西。
因此,我基本上是在尝试让 CommonJS require()
方法在浏览器端工作,这正是 Yabble 应该做的。我真的不知道从哪里开始。除了在 Yabble's Github readme 中找到的内容之外,我似乎找不到任何文档,这并没有多大帮助。
基本上我所做的就是把它放在一个 HTML 页面中......
<script src="yabble.js"></script>
<!-- Uses require -->
<script>
require.setModuleRoot('http://localhost:8030/')
my_module = require('my_module')
</script>
但是每当我调用 require()
函数时,我都会得到一个 Synchronous require() is not supported.
异常抛出。
有人可以帮助我开始吗?我应该在哪里加载 yabble.js
我应该在哪里调用 require?是否有一种特殊的方式来运行我的 Javascript 模块?
最佳答案
当将需要使用 require()
函数的 Javascript 代码加载到浏览器中时,该代码的入口点必须是 require.run()
函数.
例如,好:
<script src="yabble.js"></script>
<script>
require.setModuleRoot('http://localhost:8030/')
require.run('my_module') // <-- Uses require() function somewhere
</script>
例如,错误(将得到 Synchronous require() is not supported
错误):
<script src="yabble.js"></script>
<script src="http://localhost:8030/my_module.js"></script> <!-- <== Use's require function somewhere -->
仅供引用,Yabble 的做法非常巧妙。它实际上会静态分析你的 Javascript 源代码,我认为基本上只是使用正则表达式来查找 require()
方法,然后尝试拉取那个 .js
脚本从服务器,然后它对该 .js
脚本进行相同的静态分析,等等。
这可能特别令人困惑,因为它实际上会加载那些 .js
脚本,即使控制逻辑意味着程序流永远不会到达 require()
函数。例如,如果你有……
if (False) { require('some_module'); }
...Yabble 将仍加载此模块。
关于javascript - Yabble入门--浏览器端CommonJS模块加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5250414/