Require js, how to call defined module? - javascript

I'm trying to define a module in requirejs and use it in another script.
I've tried a lot of things, but I cannot achieve what I want.
At the moment this is what I have.
define([],{
return {
functionOne: function(){etc, etc...}
functionTwo: function(){etc, etc...}
}
})
Then I put this in the configuration file:
requirejs.config({
paths: {myModule: pathToMyModule}
})
And then, this in the script where I want to use this module
requirejs(["myModule"], function(){
//Some code
})
But I'm still getting this errors when I try to use the defined module:
myModule is not defined.
functionOne is not defined.
functionTwo is not defined.
Am I missing something?
Thank you.

To declare your module, you need to use a function, so the first line in myModule.js should look like this:
define([], function () { // ...
When you're invoking the module, you need to declare it as an argument, so your requirejs call should look like this:
requirejs(["myModule"], function (myModule) {
// ^^^^^^^^
// Notice the argument declaration
The following worked for me:
// myModule.js
define([], function () {
return {
functionOne: function(){
console.log("Hello, world. I'm functionOne.");
},
functionTwo: function(){
console.log("Hello, world. I'm functionTwo.");
}
}
});
// require.config.js
requirejs.config({
paths: { myModule: './myModule' }
});
// index.js
requirejs(["myModule"], function (myModule) {
myModule.functionOne();
myModule.functionTwo();
})

Related

requirejs defining modules not working as expected

i have the following scenario:
i have a global namespace called fort which has a few common functions that i need and it looks like this :
fort.js
define("fort", ["fortHistory"], function (FortHistory) {
function Fort(){}
Fort.prototype.history = FortHistory;
return Fort;
});
fortHistory is a small module i created defined as so:
fortHistory.js
"use strict";
define("fortHistory", function () {
function FortHistory() {
}
FortHistory.prototype.doSomething = function(){...}
return FortHistory;
});
i then do this in my config.js
require.config( {
enforceDefine: true,
paths: {
'fort': 'develop/js/fort',
'fortHistory' : 'develop/js/webapp/fortHistory'
},
shim: {
fort:{
exports: 'fort'
}
}
} );
define( function() {} );
finally in main.js i have:
define('fort', [], function(fort){
window.fort = fort;
});
the hope was that i could then make a call such as :
fort.fortHistory.doSomething();
instead fort is undefined so i am assuming i have misinterpreted how requirejs works
You've named it history, not fortHistory:
Fort.prototype.history = FortHistory;
Try calling it via fort.history.doSomething();.

Fetch requirejs.config from Gruntfile

Is there any way to import a requirejs config in to my grunt config file? Right now I have to keep two identical versions, one in app/main.js and one in my Gruntfile.js:
module.exports = function(grunt) {
// can I import app/main.js requireConfig here?
var requireConfig = {
paths: {
jquery: 'lib/jquery'
// etc...
}
};
});
My main.js looks something like this:
requirejs.config({
paths: {
jquery: 'lib/jquery'
// etc...
}
});
define(['app'], function(app){
app.start();
});
You can use standard module pattern which supports different type of module system like following.
Your requirejs config file like this
amd-config.js
(function(factory) {
if (typeof define === 'function' && define.amd) {
// Register as an AMD module if available...
define('amd-config', [], factory());
} else if (typeof exports === 'object') {
// Next for Node.js, CommonJS, browserify...
module.exports = factory();
} else {
// setting browser global when none of the above are available
window.amdConfig = factory();
}
}
(function() {
var amdConfig = {
baseUrl: 'scripts',
paths: {
//Paths here
}
};
return amdConfig;
}));
In gruntfile you can just require like any other module.
var requireConfig = require('amd-config');
Include it normally like you do in index.html with script tag before app.js
and then in app.js use it like following.
requirejs.config(window.amdConfig);
define(['app'], function(app){
app.start();
});
PS: There are cleaner way of including it in app.js.
More cleaner than second, create global variable require and include the script before requirejs script. requirejs checks if there is global variable with name require containing object. If its there, it is used as a config object. So you dont have to call requirejs.config yourself.
You can require the file like you require other files. In that case it will be treated as a require module and you will receive the object in require callback. call your requirejs.config like following.
```
require(['amd-config'], function(amdConfig){
requirejs.config(amdConfig);
require(['app'], function(app){
app.start();
});
});
```
A simpler approach you could use, if you are using grunt to build the project. You can simply use:
options:{
mainConfigFile: "path/to/Config.js"
}
granted you need to use:
https://github.com/gruntjs/grunt-contrib-requirejs
You can try something like this:
function getRequireConfig(requireFilePath) {
var config;
var configFileContent,
_require;
_require = require;
require = {
data: {},
config : function (configParam) {
this.data = configParam;
},
get : function () {
return this.data;
}
};
configFileContent = readFileSync(requireFilePath);
eval(configFileContent);
config = require.get();
require = _require;
return config;
}
What it is doing is:
Override require definition to a custom implementation
Load require config file
Eval it so that the config function of custom implementation will be
called Get the config object from data

Attempting to test require module returns undefined for anything

I'm new at unit testing but I've tried many methods of getting my script (require module) loaded for use with my mocha test script. No matter what I do I always get undefined when I try to read a property or function or anything. Can anyone help point out what may be causing this?
rmq.js (script to test)
define(['bx_slider/1/bx_slider'], {
...
ansrTotal: 0,
...
init: function(settings) {
var self = this;
// do some stuff
return self;
}
});
test-bootstrap.js
require.config({
paths: {
'chai': '/node_modules/chai/chai',
'bx_slider/1/bx_slider': '/test/lib/bx_slider'
},
baseUrl: '/',
nodeRequire: require
});
mocha.setup({
ui: 'bdd'
});
require(['test/test'], function() {
if (window.mochaPhantomJS) {
mochaPhantomJS.run();
} else {
mocha.run();
}
});
test.js
define(['chai'], function(chai) {
var expect = chai.expect;
var rmq = require(['../src/js/rmq']);
describe('rmq test suite', function() {
before(function() {
return rmq.init();
});
it('should blah', function() {
expect(rmq.ansrTotal).to.equal(0);
});
});
});
If it helps, my directory structure is
.
/node_modules
/src
/js
rmq.js
/test
/lib
bx_slider.js
require.js
test-bootstrap.js
test.js
The exact error (for what I have currently written and posted here) in my CLI is
Testing: test/test.js
rmq test suite
"before all" hook
'undefined' is not a function (evaluating 'rmq.init()')
As Mathletics mentioned in a comment, you could do:
define(['chai', '../src/js/rmq'], function(chai, rmq) {
If, for some reason, you cannot do that, there's an alternative. (Maybe you simplified your code so much in your question that the reason is no longer apparent.)
define(['chai'], function(chai) {
var expect = chai.expect;
describe('rmq test suite', function() {
var rmq;
before(function (done) {
require(['../src/js/rmq'], function (_rmq) {
// Save the module we got to the `rmq` variable.
rmq = _rmq;
// Init and call `done` when finished.
rmq.init().then(done);
});
});
it('should blah', function() {
expect(rmq.ansrTotal).to.equal(0);
});
});
});
I have assumed that rmq.init() returns a promise since you did return rmq.init() in your code, and doing this does not make sense unless rmq.init() returns a promise. If that's not the case then you'd have to call rmq.init() and then call done() after it.
The code you had cannot work because require(['../src/js/rmq']) gets the module asynchronously so it does not return the module. You have to use it like I've shown above.

How to call RequireJS functions in other files? How to separate RequireJS files?

Instead of having one giant js file that has a whole bunch of "defines", how do I call my various "define" functions from other files?
I've been copying these examples, but still cannot get it to work:
example-multipage
example-multipage-shim
example-jquery-shim
Here is what I have so far:
main.js
require.config({
baseUrl: '',
paths: {
jquery: '../libraries/jquery-1.10.2.min',
simControlView: '../javascripts/simControlView'
}
});
require(['jquery','loadPage'], function( $,loadPage)
{
loadPage();
});
define('loadPage', ['jquery'], function($)
{
var simControlView = require(['./simControlView']);
return function()
{
simControlView.showSimControlView(); //having problem here
};
});
simControlView.js
define(['jquery'], function ($) {
return {
showSimControlView: function () {
console.log("Hi!!");
}
}
});
Here is the error that I'm getting:
Uncaught TypeError: Object function d(e,c,h){var
g,k;f.enableBuildCallback&&(c&&H(c))&&(c.__requireJsBuild=!0);if("string"===typeof
e){if(H(c))return v(A("requireargs", "Invalid require
call"),h);if(a&&s(N,e))return Ne;if(j.get)return
j.get(i,e,a,d);g=n(e,a,!1,!0);g=g.id;return!s(r,g)?v(A("notloaded",'Module
name "'+g+'" has not been loaded yet for context: '+b+(a?"":". Use
require([])"))):r[g]}K();i.nextTick(function(){K();k=q(n(null,a));k.skipMap=f.skipMap;k.init(e,c,h,{enabled:!0});C()});return
d} has no method 'showSimControlView'
See anything I'm doing wrong? Any help is appreciated!
Try moving all the dependencies to the dependency list you pass to define().
Also, the ordering may be important. I.e. the define() of a module may need to come before the require() that requires it (talking about the 'loadPage' module).
Also, if your paths config calls a module 'simControlView', then it needs to be referred to as 'simControlView', and not as './simControlView'.
E.g.:
define('loadPage', ['jquery', 'simControlView'], function($, simControlView) {
return function() {
simControlView.showSimControlView();
};
});
require(['jquery', 'loadPage'], function($, loadPage) {
loadPage();
});

failing to fetch method requireJS

I am experiencing some strange issue. I have this
require({
paths: {
'template': 'tmpl.min',
'videoupload.widget': 'jquery.ui.videoupload'
}
}, ['js/main_video.js'], function(App) {
App.initial_video_upload();
});
and this
define(['template','videoupload.widget'],function() {
function initial_video_upload(){
'use strict';
$('#videoupload').videoupload({
//...some code
});
}
return{
initial_video_upload: initial_video_upload
}
}
);
in the file jquery.ui.videoupload.js, I have some call to a tmpl method which is defined in tmpl.min.js, but I get the message
Uncaught TypeError: Object [object Object] has no method 'tmpl'
There are two issues here:
Your first snippet is passing configuration options to a require function. require, is a way to load dependencies and execute some code using them. If you want to pass configuration options to require.js, requirejs.config is what you want:
// configurations to be used in your module definitions
requirejs.config({
paths: {
'template': 'tmpl.min',
'videoupload.widget': 'jquery.ui.videoupload'
}
});
// load your main module and kick things off
require(['js/main_video.js'], function(App) {
App.initial_video_upload();
});)
Your second snippet is declaring dependencies, but not passing them into the callback:
define(['template','videoupload.widget'],
// these are now accessible within the function's scope:
function(template, videoupload.widget) {
function initial_video_upload(){
'use strict';
$('#videoupload').videoupload({
//...some code
});
}
return{
initial_video_upload: initial_video_upload
}
}
);
Additionally, I'm assuming jQuery is a dependency of your videoupload.widget. How are you loading that? You may need to add an additional "shim" configuration to your requirejs.config:
requirejs.config({
paths: {
'template': 'tmpl.min',
'videoupload.widget': 'jquery.ui.videoupload'
},
shim: {
"videoupload.widdget": ["jquery"]
}
});

Categories