【问题标题】:Module not defined模块未定义
【发布时间】:2016-02-26 19:19:04
【问题描述】:

我正在学习 Javascript 和 Node,我正在尝试创建一个扩展 String 的模块。首先我得到错误require is not defined所以我开始使用requireJS。然后我收到了这个错误NS_ERROR_DOM_BAD_URI: Access to restricted URI denied 所以我将project.html 移动到与我的.js 文件相同的文件夹中。现在我得到了require.js 中未定义的模块,我似乎无法弄清楚为什么。我已经阅读了其他一些帖子,但我没有找到解决方案。我的文件结构是这样的

  • 条/
    • 脚本/
    • main.js
    • require.js
    • project.html
    • 帮手/
      • extendString.js

ma​​in.js

define(function(require, exports, module){
  var StringHelperModule = require("helper/extendString.js");
  StringHelperModule.extendString(String);

  var tmp = 'Hello World'.strip(' ');
  document.write(tmp);
  //Outputs: HelloWorld
});

extendString.js

'use strict';
module.exports = function extendString(String){
  String.prototype.strip = function (delimiter) {
    return this.replace(delimiter, '');
  };
};

project.html

<!DOCTYPE html>
<html>
   <head>
      <script data-main='main' src='require.js'></script>
   </head>
</html>

require.js

(function () {
    // Separate function to avoid eval pollution, same with arguments use.
    function exec() {
        eval(arguments[0]); //This is line the error points to
    }

    require.load = function (context, moduleName, url) {
        var xhr = new XMLHttpRequest();

        xhr.open('GET', url, true);
        xhr.send();

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                exec(xhr.responseText);

                //Support anonymous modules.
                context.completeLoad(moduleName);
            }
        };
    };
}());

在它说模块未定义之前我也变得不规范,如果这与此有关

【问题讨论】:

  • 你试过了吗:require("./helper/extendString.js");? (注意开头的点)
  • @leo.fcx 是的,但没有帮助。我刚刚在 requirejs 网站上发现了一个可能是我的问题的常见错误,但我不确定如何解决它。 error

标签: javascript node.js requirejs


【解决方案1】:

我认为您在这里混合了模块格式,您的模块看起来更像 CommonJS,而不是 AMD 格式。

define(function(require, exports, module) {
  'use strict';

  module.exports = function extendString () {
    String.prototype.strip = function (delimiter) {
      return this.replace(delimiter, '');
    };
  };
});

然后,在你的 main.js 中,你应该使用 require(),而不是 define()。 另外,请注意,您不需要将 String 传递给函数,它是全局的。

require(
  ['path/to/extendString'],
    function (extendString) {
      extendString(); // add the methods to String.prototype
      console.log('Hello awesome world!'.strip(' '));
    }
);

应该可以的。

【讨论】:

  • 消除了模块错误。现在我只需要弄清楚为什么它说strip 不是一个函数。谢谢!
  • 可能是因为您应该在尝试访问新添加的方法之前调用 extendString()。或者您可以直接在定义中添加方法,而不是在 module.exports 中。
  • 啊,我想通了。您介意在使用它的情况下将此添加到您的答案中吗? extendString(); 然后document.write('Hello World'.strip(' ')); 这将是一个非常好的和完整的答案
猜你喜欢
  • 2021-12-31
  • 2018-10-09
  • 2015-06-21
  • 2021-01-06
  • 2021-07-17
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多