Reputation: 2700
I'm learning Javascript and Node and I am trying to create a module that extends String. First I got the error require is not defined so I started using requireJS. Then I got this error NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
so I moved project.html
into the same folder as my .js
files. Now I am getting module not defined in require.js
and I can't seem to figure out why. I've read through some other posts but I didn't find a solution. My file structure looks like this
- strip/
- scripts/
- main.js
- require.js
- project.html
- helper/
- 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);
}
};
};
}());
I'm also getting not well-formed before it says module not defined if that has anything to do with this
Upvotes: 1
Views: 12393
Reputation: 616
I think you're mixing module formats here, your module looks more like CommonJS, than AMD format.
define(function(require, exports, module) {
'use strict';
module.exports = function extendString () {
String.prototype.strip = function (delimiter) {
return this.replace(delimiter, '');
};
};
});
Then, in your main.js, you should use require(), instead of define(). Also, note, that you don't need to pass String to function, it's global.
require(
['path/to/extendString'],
function (extendString) {
extendString(); // add the methods to String.prototype
console.log('Hello awesome world!'.strip(' '));
}
);
That should work.
Upvotes: 3