2016-02-26 141 views
0

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

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

main.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); 
      } 
     }; 
    }; 
}()); 

我也越来越没有很好地形成,它说如果有任何与此

+1

您是否试过:require(“./ helper/extendString.js”);'? (注意开头的点) –

+0

@ leo.fcx是的,它没有帮助。我刚刚在requirejs网站上发现了一个可能是我的问题的常见错误,但我不知道如何解决它。 [error](http://requirejs.org/docs/errors.html#defineerror) – SirParselot

回答

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,你应该使用要求(),而不是定义()。 另外,请注意,您不需要将String传递给函数,它是全局的。

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

这应该有效。

+0

摆脱了模块错误。现在我只需要弄清楚它为什么说'strip'不是一个函数。谢谢! – SirParselot

+0

也许是因为您应该在尝试访问新添加的方法之前调用extendString()。或者你可以在define中添加方法,而不是在module.exports里面。 –

+0

啊我想通了。你介意在使用它的过程中添加这个答案吗? 'extendString();'然后'document.write('Hello World')。(''));'这将是一个非常好的和完整的答案 – SirParselot