如何使用JS require()而不使用Node.js

这可能是一个蹩脚的问题,但是如何在常规JavaScript中实现与require() (Node.js)相同的function呢?

有些帮助真的会被赞赏。

有几个服务,让你这样做。

最受欢迎的是Browserify 。

基本上,它需要通过语法树读取文件并将其转换为与RequireJS类似的样式。

请注意,这需要一个额外的编译步骤。 (我们最终会在ES6中获取模块,尽pipe如此:))

http://requirejs.org/docs/start.html

存在一个叫做RequireJS的模块加载器,可以在不使用Node.js或Rhino的情况下在浏览器中使用。

要使用它,请下载并保存脚本并将其包含在您的页面中

 <!DOCTYPE html> <html> <head> <title>My Sample Project</title> <!-- data-main attribute tells require.js to load scripts/main.js after require.js loads. --> <script data-main="scripts/main" src="scripts/require.js"></script> </head> <body> <h1>My Sample Project</h1> </body> </html> 

data-main属性将指向您的主脚本,您可以在其中使用以下命令加载脚本的其余部分:

 require(["helper/util"], function(util) { //This function is called when scripts/helper/util.js is loaded. //If util.js calls define(), then this function is not fired until //util's dependencies have loaded, and the util argument will hold //the module value for "helper/util". }); 

http://requirejs.org上查看文档以获取更多信息&#x3002;