【问题标题】:How to use JS require() without Node.js如何在没有 Node.js 的情况下使用 JS require()
【发布时间】:2014-03-16 03:04:14
【问题描述】:

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

我们将不胜感激。

【问题讨论】:

  • 你必须使用 eval 和同步 ajax 来重新创建 node.js 的 require() 函数。不用说,大多数开发者都不喜欢这两者,所以他们使用不太方便的异步导入,例如 yepnope、requireJS、AMD 等。

标签: javascript node.js require


【解决方案1】:

有多种服务可让您执行此操作。

最受欢迎的是Browserify

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

请注意,这需要额外的编译步骤。 (我们最终会在 ES6 中获得模块,所以就是这样 :))

【讨论】:

  • 2017 - 最受欢迎的是 webpack
【解决方案2】:

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查看文档以获取更多信息。

【讨论】:

  • 非常感谢! requirejs 对我来说很好用。我正在使用 gulp 将节点模块 concat + uglify 到一个文件(例如:script.min.js)并使用 requirejs 正确编译模块。
猜你喜欢
  • 2014-03-21
  • 2017-11-05
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多