I'm writing a modular web app using RequireJS for module loading and dependency injection.
From my bootstrap.js file I load Application.js and initialize it, passing in an array of modules that are to be "loaded"(1) by the Application. When the initialization finishes, the Application will call a function to signal that it's done loading.
I'm loading the modules asynchronously (in regard to each other) using require(["module"], callback(module), callback(error)).
The problem that I'm having with this is that the error callback (errback) is not called when a module fails to load (at least on Chrome when the server responds with a 404 status code).
I can see the error in the Google Chrome Developer Tools Console, but the errback isn't called:
GET http://192.168.1.111:8812/scripts/modules/InexistentModule/manifest.js 404 (Not Found)
Uncaught Error: Load timeout for modules: modules/InexistentModule/manifest
Has anyone experienced gotten around this issue with RequireJS errbacks? If so, how?
(1) Actually, I'm just loading module manifests, not the entire modules, so that I can display icons for them and register their routes using Backbone.SubRoute
The libraries that I'm using (none of them are minified):
RequireJS 1.0.8
Underscore 1.6.0
jQuery 1.11.0
Backbone 1.1.2
Backbone.SubRoute 0.4.1
Out of the libraries above, only RequireJS and Underscore are used directly by me at the moment.
I've used Underscore for currying when passing the success/failure callbacks to Require in order to pass in the i from my loop as the index parameter. For the success callback, this works wonderfully and I think that this does not affect the errback (I've tested with a simple function of arity 1, instead of the partial function returned by _.partial and the function is still not called in case of a 404 error).
I'll post my bootstrap.js and Application.js files here as they might provide more info on this.
Thank you!
bootstrap.js
require.config({
catchError: true,
enforceDefine: true,
baseUrl: "./scripts",
paths: {
"jquery": "lib/jquery",
"underscore": "lib/underscore",
"backbone": "lib/backbone",
"backbone.subroute": "lib/backbone.subroute"
},
shim: {
"underscore": {
deps: [],
exports: "_"
},
"backbone": {
deps: ["jquery", "underscore"],
exports: "Backbone"
},
"backbone.subroute": {
deps: ["backbone"],
exports: "Backbone.SubRoute"
}
}
});
define(["jquery", "underscore", "backbone", "Application"],
function ($, _, Backbone, Application) {
var modules = ["Home", "ToS", "InexistentModule"];
var defaultModule = "Home";
var onApplicationInitialized = function()
{
require(["ApplicationRouter"], function(ApplicationRouter){
ApplicationRouter.initialize();
});
}
Application.initialize(modules, defaultModule, onApplicationInitialized);
}
);
Application.js
define([
'jquery',
'underscore',
'backbone'],
function($,_,Backbone){
var modules;
var manifests = [];
var routers = [];
var defaultModule = "";
var totalModules = 0;
var loadedModules = 0;
var failedModules = 0;
var onCompleteCallback = function(){};
var onModuleManifestLoadComplete = function(index, manifest){
manifests[index] = manifest;
console.log("Load manifest for module: " + modules[index] + " complete");
//TODO: init module
loadedModules++;
if(totalModules == (loadedModules + failedModules))
onCompleteCallback();
};
var onModuleManifestLoadFailed = function(index, err){
console.log("Load manifest for module: " + modules[index] + " failed");
failedModules++;
if(totalModules == (loadedModules + failedModules))
onCompleteCallback();
};
var initialize = function(_modules, _defaultModule, callback){
defaultModule = _defaultModule;
modules = _modules;
manifests = Array(modules.length);
totalModules = modules.length;
onCompleteCallback = callback;
for(i=0; i<modules.length; i++){
require(['modules/'+modules[i]+'/manifest'],
_.partial(onModuleManifestLoadComplete, i),
_.partial(onModuleManifestLoadFailed, i));
};
};
return {
modules: modules,
manifests: manifests,
routers: routers,
defaultModule: defaultModule,
initialize: initialize
};
});
You indicate you are using RequireJS 1.0.8. I've checked the documentation for the 1.x series and find nothing about errbacks. This page actually indicates that errbacks were introduced in the 2.x series.
Also the shim is something that was introduced in the 2.x series. So right now, RequireJS is ignoring your shims.
Related
I have a web app using RequireJS. Here is my js/main.js file:
require.config({
baseUrl: 'js/',
paths: {
jquery: 'libs/jquery/jquery',
lodash: 'libs/lodash/lodash',
backbone: 'libs/backbone/backbone',
// [other dependencies...]
}
});
require(['views/AppView'], function (AppView) {
var app_view = new AppView;
});
here is my js/views/AppView.js file:
define([
'jquery',
'underscore',
'backbone',
'joint',
'views/ProjectView',
'models/Command',
'views/detailsview',
'views/newcellview'
], function ($, _, Backbone, joint, ProjectView, Command, DetailsView, NewCellView) {
var app_view = {stub: 'stub'};
return app_view;
});
and finally here is my AppViewTest.js file which I run with mocha js/test/AppViewTest.js:
var assert = require('assert');
var requirejs = require('requirejs');
describe('AppView', function() {
var app_view;
beforeEach(function (done) {
requirejs(['../views/AppView.js'], function (AppView) {
app_view = new AppView;
});
});
it('should be [...]', function() {
assert.equal(app_view, ...);
});
});
I get the following error:
1) AppView views "before each" hook:
Uncaught Tried loading "jquery" at /usr/local/lib/node_modules/mocha/bin/jquery.js then tried node's require("jquery") and it failed with error: Error: Cannot find module 'jquery'
You start your test with:
var assert = require('assert');
var requirejs = require('requirejs');
and then you start making calls to requirejs but there's nothing in here that configures RequireJS.
If you cut and paste the require.config call you have in your main.js into your test file, that would configure your test for loading the same files as you have in your regular application.
Another way to do it would be:
before(function (done) {
requirejs(['full-path-to/main'], function () {
requirejs(['../views/AppView'], function (AppView) {
app_view = new AppView;
done();
});
});
});
The point is to load your configuration before you load your AppView. Note also that you need to call done, and I've changed beforeEach to before because there's no need to reload it before each test. (It was a slip of the mind earlier when I induced you to use beforeEach. My bad.)
I've also removed the .js from your requirejs call because you should not use .js. Sometimes it is warranted but unless you can explain why you need it, you should not use it.
I have a JavaEE project that uses RequireJS to load a few third party frameworks. One of those frameworks is OpenLayers3. Openlayers3 natively creates a global "ol" variable. However, OpenLayers3 is written to be AMD compatible and works as a module through RequireJS. I also am using an OpenLayers3 plugin called "olLayerSwitcher" which is not optimized for AMD. Instead, it depends on the "ol" variable being global.
My require config looks like the following:
paths: {
"sinon": ['/webjars/sinonjs/1.7.3/sinon'],
"jquery": ["/webjars/jquery/2.1.4/jquery"],
"backbone": ['/webjars/backbonejs/1.2.1/backbone'],
"underscore": ['/webjars/underscorejs/1.8.3/underscore'],
"text": ['/webjars/requirejs-text/2.0.14/text'],
"log4js": ['/webjars/log4javascript/1.4.13/log4javascript'],
"ol": ['/webjars/openlayers/3.5.0/ol'],
"olLayerSwitcher": ['/js/vendor/ol3-layerswitcher/1.0.1/ol3-layerswitcher']
},
shim: {
"olLayerSwitcher": {
deps: ["ol"],
exports: "olLayerSwitcher"
},
'sinon' : {
'exports' : 'sinon'
}
}
The project is uses Backbone and includes a Router module (/src/main/webapp/js/controller/AppRouter.js):
/*jslint browser : true*/
/*global Backbone*/
define([
'backbone',
'utils/logger',
'views/MapView'
], function (Backbone, logger, MapView) {
"use strict";
var applicationRouter = Backbone.Router.extend({
routes: {
'': 'mapView'
},
initialize: function () {
this.LOG = logger.init();
this.on("route:mapView", function () {
this.LOG.trace("Routing to map view");
new MapView({
mapDivId: 'map-container'
});
});
}
});
return applicationRouter;
});
The Router module depends on a View module (/src/main/webapp/js/views/MapView.js):
/*jslint browser: true */
define([
'backbone',
'utils/logger',
'ol',
'utils/mapUtils',
'olLayerSwitcher'
], function (Backbone, logger, ol, mapUtils, olLayerSwitcher) {
"use strict";
[...]
initialize: function (options) {
this.LOG = logger.init();
this.mapDivId = options.mapDivId;
this.map = new ol.Map({
[...]
controls: ol.control.defaults().extend([
new ol.control.ScaleLine(),
new ol.control.LayerSwitcher({
tipLabel: 'Switch base layers'
})
])
});
Backbone.View.prototype.initialize.apply(this, arguments);
this.render();
this.LOG.debug("Map View rendered");
}
});
return view;
});
The View module attempts to pull in both OpenLayers3 as well as the third-party OpenLayers plugin.
When the project is built and deployed, it works fine in-browser. When the View module is loaded, OpenLayers and the third-party plugin are pulled in just fine and everything renders properly.
However, when I attempt to test this in Jasmine is where all of this falls apart.
For Jasmine, I am using the Jasmine-Maven plugin. It pulls in JasmineJS, PhantomJS and RequireJS along with my libraries and runs my specs. The issue is that when run via Jasmine, the MapView module attempts to load both the OpenLayers3 library as well as the third party plugin (olLayerSwitcher) but fails because the third party plugin can't find "ol".
The test:
define([
"backbone",
"sinon",
'controller/AppRouter'
], function (Backbone, sinon, Router) {
describe("Router", function () {
beforeEach(function () {
this.router = new Router();
this.routeSpy = sinon.spy();
this.router.bind("route:mapView", this.routeSpy);
try {
Backbone.history.start({silent: true});
} catch (e) {
}
this.router.navigate("elsewhere");
});
it("does not fire for unknown paths", function () {
this.router.navigate("unknown", true);
expect(this.routeSpy.notCalled).toBeTruthy();
});
it("fires the default root with a blank hash", function () {
this.router.navigate("", true);
expect(this.routeSpy.calledOnce).toBeTruthy();
expect(this.routeSpy.calledWith(null)).toBeTruthy();
});
});
});
The error from Jasmine:
[ERROR - 2015-08-08T21:27:30.693Z] Session [4610ead0-3e14-11e5-bb2b-dd2c4b5c2c7b] - page.onError - msg: ReferenceError: Can't find variable: ol
:262 in error
[ERROR - 2015-08-08T21:27:30.694Z] Session [4610ead0-3e14-11e5-bb2b-dd2c4b5c2c7b] - page.onError - stack:
global code (http://localhost:58309/js/vendor/ol3- layerswitcher/1.0.1/ol3-layerswitcher.js:9)
:262 in error
JavaScript Console Errors:
* ReferenceError: Can't find variable: ol
The relevant section from the ol3-layerswitcher plugin on line 9 is:
[...]
ol.control.LayerSwitcher = function(opt_options) {
[...]
So it does depend on "ol" being a thing at this point.
The Jasmine-Maven plugin creates its own spec runner HTML and the relevant portion looks like this:
<script type="text/javascript">
if(window.location.href.indexOf("ManualSpecRunner.html") !== -1) {
document.body.appendChild(document.createTextNode("Warning: Opening this HTML file directly from the file system is deprecated. You should instead try running `mvn jasmine:bdd` from the command line, and then visit `http://localhost:8234` in your browser. "))
}
var specs = ['spec/controller/AppRouterSpec.js'];
var configuration = {
paths: {
"sinon": ['/webjars/sinonjs/1.7.3/sinon'],
"jquery": ["/webjars/jquery/2.1.4/jquery"],
"backbone": ['/webjars/backbonejs/1.2.1/backbone'],
"underscore": ['/webjars/underscorejs/1.8.3/underscore'],
"text": ['/webjars/requirejs-text/2.0.14/text'],
"log4js": ['/webjars/log4javascript/1.4.13/log4javascript'],
"ol": ['/webjars/openlayers/3.5.0/ol'],
"olLayerSwitcher": ['/js/vendor/ol3-layerswitcher/1.0.1/ol3-layerswitcher']
},
shim: {
"olLayerSwitcher": {
deps: ["ol"],
exports: "olLayerSwitcher"
},
'sinon' : {
'exports' : 'sinon'
}
}
};
if (!configuration.baseUrl) {
configuration.baseUrl = 'js';
}
if (!configuration.paths) {
configuration.paths = {};
}
if (!configuration.paths.specs) {
var specDir = 'spec';
if (!specDir.match(/^file/)) {
specDir = '/'+specDir;
}
configuration.paths.specs = specDir;
}
require.config(configuration);
require(specs, function() {
jasmine.boot();
});
I am able to create a customer HTML runner but am not sure what the problem is so I wouldn't know what needs changing.
This doesn't seem to be a PhantomJS issue as I can load the tests in-browser and am experiencing the same issue.
I'd appreciate if anyone has any thoughts on what could be happening here. I really do not want to hack up the third-party module to transform it into a RequireJS module as the Jasmine testing is the last-leg of implementing this completely and I'm completely stuck here.
I am using Jasmine 2.3.0 and RequireJS 2.1.18
I apologize for not linking out more but this is a new account and I don't have enough rep for it.
It will be tough to figure out the problem without a running version of your setup.
However, if you're able to customize the SpecRunner.html for jasmine generated by the maven plugin, simply include the jasmine(/ any other library causing an issue) in the SpecRunner html - <script src="/<path_to_lib>">.
In my experience, its usually not worth the effort , to make libraries used in source amd compliant and play nicely with every other library for testing setup.
I'm new to working with RequireJS, and am trying to figure out shimming 3rd-party, interdependent scripts. Specifically, I'm trying to get the Stanford Crypto scripts imported.
Basically, the suite is comprised of the core (jsbn.js, jsbn2.js, base64.js, rng.js, and prng4.js), a basic RSA script (rsa.js), and an extended RSA script (rsa2.js).
rsa.js defines the global variable-object RSAKey, and rsa2.js references it.
function RSAKey() {
this.n = null;
this.e = 0;
this.d = null;
this.p = null;
this.q = null;
this.dmp1 = null;
this.dmq1 = null;
this.coeff = null;
}
I've set up my shim in a way that I thought was correct, but I get the error "RSAKey is not defined" in rsa2.js. The following is my shim:
require.config({
paths: {
'jsbn': "../StanfordRSA/jsbn.js",
'jsbn2': "../StanfordRSA/jsbn2.js",
'base64': "../StanfordRSA/base64.js",
'rng': "../StanfordRSA/rng.js",
'prng4': "../StanfordRSA/prng4.js",
'rsa': "../StanfordRSA/rsa.js",
'rsa2': "../StanfordRSA/rsa2.js"
},
shim: {
'rsa': {
deps: ['jsbn', 'jsbn2', 'base64', 'rng', 'prng4'],
exports: "RSAKey"
},
'rsa2': {
deps: ['rsa']
}
}
});
My understanding, then, is that if I set 'rsa2' as a requirement in one of my RequireJS modules, it would look at the shim and see that rsa2 is dependent on rsa, which is dependent on the core and exports RSAKey...But that's not what's happening, and it seems like either rsa isn't loading, or it isn't loading correctly. (Please note that all of this works using raw script tags. I'm trying to convert an already existing, already functioning webapp to RequireJS)
Thoughts?
Your basic setup is correct, except for 2 things:
(really important!) You have to omit the .js extensions!!!
You probably have missed the exact dependencies between the scripts.
After some experimentation and reading the comments at the top of the scripts, the working configuration is:
require.config({
paths: {
'jsbn': "../StanfordRSA/jsbn",
'jsbn2': "../StanfordRSA/jsbn2",
'base64': "../StanfordRSA/base64",
'rng': "../StanfordRSA/rng",
'prng4': "../StanfordRSA/prng4",
'rsa': "../StanfordRSA/rsa",
'rsa2': "../StanfordRSA/rsa2"
},
shim: {
'rng': {
deps: ['prng4']
},
'jsbn2': {
deps: ['jsbn']
},
'rsa': {
deps: ['jsbn', 'rng'],
exports: 'RSAKey'
},
'rsa2': {
deps: ['rsa', 'jsbn2'],
exports: 'RSAKey'
}
}
});
Check out a plunk here.
I'm using RequireJS (version 2.1.14) and would like to concatenate my JavaScript files into one single app-built.js.
I've created a little node module which reads my app.js, extracts the project paths and gets executed once I run node build in the js directory of my application.
The node module (build.js):
var fs = require('fs'),
path = require('path'),
directory = __dirname + path.sep,
requirejs = require(directory + 'vendor/r.js');
fs.readFile(directory + 'app.js', 'utf8', function(err, data) {
if (err) {
console.log('Error: ' + err);
return
} else {
data = data.replace(/'/g, '"').replace(/\s+/g, '');
var paths = data.substr(data.indexOf('{'), data.indexOf('}')),
paths = paths.substr(0, paths.indexOf('}') + 1),
paths = JSON.parse(paths);
createAppBuilt(paths);
}
});
function createAppBuilt(paths) {
var config = {
baseUrl: __dirname,
paths: paths,
name: 'app',
out: 'app-built.js',
preserveLicenseComments: false,
findNestedDependencies: true,
removeCombined: true
};
requirejs.optimize(config, function(buildResponse) {
var contents = fs.readFileSync(config.out, 'utf8');
console.log('Created app-built.js');
}, function(err) {
console.log('Error: ' + err);
return;
});
}
app.js:
var paths = {
'jquery': 'vendor/jquery-1.11.0.min',
// other paths
};
// Set language, necessary for validtaion plugin -> validation.js
if (Modernizr.localstorage) {
localStorage.getItem('language') || localStorage.setItem('language', navigator.language || navigator.userLanguage);
}
requirejs.config({
paths: paths,
shim: {
touchswipe: {
deps: ['jquery']
},
icheck: {
deps: ['jquery']
},
validate: {
deps: ['jquery']
},
mask: {
deps: ['jquery']
},
chosenImage: {
deps: ['jquery', 'chosen']
},
cookie: {
deps: ['jquery']
}
}
});
require(['globals', 'jquery', 'underscore'], function() {
var initial = ['main'];
if (!Modernizr.localstorage) {
initial.push('cookie');
}
require(initial, function(Main) {
$(function() {
if (!Modernizr.localstorage) {
$.cookie.json = true;
}
Main.init();
});
});
});
The app-built.js gets generated but when I include it in my index.php all the other modules get loaded as well. How can I prevent the loading of all modules and only load the app-built.js?
I recommend you look into http://webpack.github.io/
or http://browserify.org/ as these solve this problem for you.
They allow you to use require much as before, yet the code is compiled/concatenated into a single file.
Webpack allows for a bit more flexibility in loading different chunks of code for different parts of your site, but Browserify is the most well-known so far.
There may be a cost in switching over to these, as I don't think that they're 100% compatible requirejs, however they bring great advantages.
Here's someone's journey from RequireJS to Browserify with some Pros and Cons.
Separate modules into different files, e.g. app-built.js, user-built.js. Then load script when it's needed.
Here's a demo: http://plnkr.co/edit/s6hUOEHjRbDhtGxaagdR?p=preview .
When page loaded, requirejs only loads global.js. After clicking the Change Color button, requirejs starts to load colorfy.js and random-color.js, which required by colorfy.js.
I am not sure about the exact details, but, yet if you don't have an exports option, r.js doesn't define a named module for you, that causes to actually load the script.
I assume you have jquery plugins there so add this extra exports option:
shim: {
touchswipe: {
deps: ['jquery'],
exports: 'jQuery.fn.touchswipe'
},
This should force r.js to build a named module for touchswipe:
define("touchswipe", (function (global) {
return function () {
var ret, fn;
return ret || global.jQuery.fn.touchswipe;
};
}(this)));
Note that, exports option might not build this named module, in that case your best bet is to include this manually.
Again I am not sure about why and how this happens, It must be a bug in requirejs, it's unlikely there is a tweak for this.
Changing the r.js optimizer (to uglify2) solved the problem for me:
var config = {
baseUrl: __dirname,
paths: paths,
name: 'app',
out: 'app-built.js',
findNestedDependencies: true,
preserveLicenseComments: false,
removeCombined: true,
optimize: 'uglify2'
};
Is there a way to set the templateSettings for lodash when using RequireJS?
Right now in my main startup I have,
require(['lodash', 'question/view'], function(_, QuestionView) {
var questionView;
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g,
evaluate: /\{\%(.+?)\%\}/g
};
questionView = new QuestionView();
return questionView.render();
});
but it doesn't seem to want to set the templateSettings globally because when I use _.template(...) in a module it wants to use the default templateSettings. The problem is that I don't want to change this setting in every module that uses _.template(...).
Based onĀ #Tyson Phalp suggestion, that means this SO question.
I adapted it to your question and I tested it using RequireJS 2.1.2 and SHIM configuration.
This is the main.js file, that is where the requireJS config is:
require.config({
/* The shim config allows us to configure dependencies for
scripts that do not call define() to register a module */
shim: {
underscoreBase: {
exports: '_'
},
underscore: {
deps: ['underscoreBase'],
exports: '_'
}
},
paths: {
underscoreBase: '../lib/underscore-min',
underscore: '../lib/underscoreTplSettings',
}
});
require(['app'],function(app){
app.start();
});
Then you should create the underscoreTplSettings.js file with your templateSettings like so:
define(['underscoreBase'], function(_) {
_.templateSettings = {
evaluate: /\{\{(.+?)\}\}/g,
interpolate: /\{\{=(.+?)\}\}/g,
escape: /\{\{-(.+?)\}\}/g
};
return _;
});
So your module underscore will contain the underscore library and your template settings.
From your application modules just require the underscore module, in this way:
define(['underscore','otherModule1', 'otherModule2'],
function( _, module1, module2,) {
//Your code in here
}
);
The only doubt I have is that I'm exporting the same symbol _ two times, even tough this work I'm not sure if this is considered a good practice.
=========================
ALTERNATIVE SOLUTION:
This also works fine and I guess it's a little bit more clean avoiding to create and requiring an extra module as the solution above. I've changed the 'export' in the Shim configuration using an initialization function. For further understanding see the Shim config reference.
//shim config in main.js file
shim: {
underscore: {
exports: '_',
init: function () {
this._.templateSettings = {
evaluate:/\{\{(.+?)\}\}/g,
interpolate:/\{\{=(.+?)\}\}/g,
escape:/\{\{-(.+?)\}\}/g
};
return _; //this is what will be actually exported!
}
}
}
You should pass your _ variable with template settings as function argument or as property in global object (window for browsers or proccess for nodejs).
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g,
evaluate: /\{\%(.+?)\%\}/g
};
questionView = new QuestionView(_);
Or
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g,
evaluate: /\{\%(.+?)\%\}/g
};
window._ = _
First option is better.
Bear in mind that if you're using underscore >=1.6.0 or lodash-amd the solution is pretty simple:
"main.js" configuration file
require.config({
baseUrl: './', // Your base URL
paths: {
// Path to a module you create that will require the underscore module.
// You cannot use the "underscore" name since underscore.js registers "underscore" as its module name.
// That's why I use "_".
_: 'underscore',
// Path to underscore module
underscore: '../../bower_components/underscore/underscore',
}
});
Your "_.js" file:
define(['underscore'], function(_) {
// Here you can manipulate/customize underscore.js to your taste.
// For example: I usually add the "variable" setting for templates
// here so that it's applied to all templates automatically.
// Add "variable" property so templates are able to render faster!
// #see http://underscorejs.org/#template
_.templateSettings.variable = 'data';
return _;
});
A module file. It requires our "_" module which requires "underscore" and patches it.
define(['_'], function(_){
// You can see the "variable" property is there
console.log(_.templateSettings);
});