Using requireJS with angular; Cannot read property 'module' of undefined - javascript

Ok, there is a bunch of questions with similar titles, but none of them helped me solve my problem so here it is.
I am trying to use Angular with RequireJS; I am getting the error message Uncaught TypeError: Cannot read property 'module' of undefined which is referring to the angular object within the angular-routes.js file. This suggests to me that requireJS is trying to load angular-routes before angular has loaded. I was under the impression that this wouldn't happen because I have set 'angular-route' as dependant on 'angular' within the shim. Can anyone spot what I am doing wrong here?
// Setup requireJS
require.config({
baseUrl : "scripts",
packages : [
{ "name":"angular", "location":"../bower_components/angular", "main":"angular"},
{ "name":"angular-route", "location":"../bower_components/angular-route", "main":"angular-route"},
{ "name":"angular-animate", "location":"../bower_components/angular-animate", "main":"angular-animate"},
{ "name":"angular-storage", "location":"../bower_components/angular-storage/dist", "main":"angular-storage"},
{ "name":"jquery", "location":"../bower_components/jquery/dist", "main":"jquery"}
],
shim:{
'angular' : { exports : 'angular', deps : ['jquery'] },
'angular-route' : { deps : ['angular'] },
'angular-animate' : { deps : ['angular'] },
'angular-storage' : { deps : ['angular'] },
}
});
// Load app files
function loadApp($, app)
{
angular.element(document).ready(function(){
angular.bootstrap(document, ['mealPlannerApp']);
});
}
requirejs(['app'], loadApp);
My app.js file is as follows
(function() {
// Declare AMD module with dependencies
define(['angular', 'angular-route', 'routes'],
function(config)
{
var app = angular.module('mealPlannerApp', ['ngRoute', 'ngAnimate', 'ngAnimate']);
app.config(config);
});
}());

Packages are great for your internal packages, I haven’t tried to load main AngularJS files as them.
Please read http://jonathancreamer.com/require-js-packages-for-building-large-scale-angular-applications/ for some better clarification and examples than change config section to something like this. Major change is replacement of packages with paths
Please also consider to change variables to camelCase style
require.config({
paths: {
angular: '../bower_components/angular/angular',
'angular-route': '../bower_components/angular-route/angular-route',
'angular-animate': '../bower_components/angular-route/angular-animate',
'angular-storage': '../bower_components/angular-route/angular-storage'
},
shim: {
'angular' : { exports : 'angular', deps : ['jquery'] },
'angular-route' : { deps : ['angular'] },
'angular-animate' : { deps : ['angular'] },
'angular-storage' : { deps : ['angular'] },
},
priority: [
"angular"
]
});

Related

r.js optmiser: $ not defined

I'm trying to use the r.js optimiser for the first time.
My main file looks like this:
/*--- Require.js: the main module loader ---*/
require.config({
baseUrl: 'assets/js',
waitSeconds: 0,
paths : {
jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min',
jqueryui : '//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min',
underscore : 'vendor/underscore/underscore-min',
backbone : 'vendor/backbone/backbone',
routefilter : 'vendor/backbone.routefilter/backbone.routefilter',
marionette : 'vendor/marionette/marionette',
tpl : 'vendor/require/tpl',
async : 'vendor/async/async',
require_async : 'vendor/require/require_async',
modernizr : 'vendor/modernizr/modernizr.custom.15872',
hello : 'vendor/hello/hello',
facebook : 'vendor/hello/facebook',
google : 'vendor/hello/google',
moment : 'vendor/moment/moment',
$dropdown : 'vendor/jquery.dropdown/jquery.dropdown',
spin : 'vendor/spin/spin',
selectBoxIt : 'vendor/selectBoxIt/selectBoxIt',
maskedinput : 'vendor/maskedinput/maskedinput',
multidatespicker : 'vendor/multidatespicker/jquery-ui.multidatespicker'
//markerclusterer : 'vendor/markerclusterer/markerclusterer'
},
shim : {
underscore: {
exports: '_'
},
backbone: {
deps : ['jquery', 'underscore'],
exports : 'Backbone'
},
marionette: {
deps : ['jquery', 'underscore', 'backbone'],
exports : 'Marionette'
},
routefilter: {
deps : ['marionette', 'backbone', 'underscore', 'jquery'],
exports : 'Routefilter'
},
selectBoxIt: {
deps : ['jquery', 'jqueryui'],
exports : 'SelectBoxIt'
},
multidatespicker: {
deps : ['jquery', 'jqueryui'],
exports : 'MultidatesPicker'
},
facebook: {
deps : ['hello'],
exports : 'Facebook'
},
google: {
deps : ['hello'],
exports : 'Google'
}
//markerclusterer: {
// exports : 'Markerclusterer'
//}
},
config: {
moment: {
noGlobal: true
}
}
});
//--- Define Google maps to make it globally accessible throughout the application ---//
define('gmaps', ['require_async!https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry,places&key=AIzaSyDRKg-SNBODA1mKMCRrfMrls48x7owr9w8&sensor=true"'],
function(){
// return the gmaps namespace for brevity
return window.google.maps;
});
//--- Define moment ---
require(["moment"], function (moment) {
moment().format();
});
// --- Initialize the application ---//
require([
'zwoop', 'backbone'
], function(Zwoop, Backbone){
Zwoop.start();
});
The build file contains the following settings:
mainConfigFile:"js/main.js",
baseUrl : "js",
name: "main",
out: "dist/main.js",
removeCombined: true,
findNestedDependencies: false,
paths: {
jquery: "empty:"
}
I don't receive any errors, but unfortunately I receive an error in the browser:
Uncaught ReferenceError: $ is not defined
It appears that either jquery is not properly loaded from the CDN, or that something is not working correctly regarding the shim.
Can you spot what the error might be?

Strange Requirejs behavior when loading Markdown

I have a requirejs module in which I am trying to load markdownjs. Here is the file:
define(function(require) {
'use strict';
var Backbone = require('backbone');
var blogCollectionTemplate = require('hbs!app.templates/blog.collection.view');
var BlogModelView = require('views/blog.item.view');
var markdown = require('markdown');
var BlogCollectionView = Backbone.View.extend({
template: blogCollectionTemplate,
initialize: function() {
debugger;
},
render: function() {
this.$el.html(this.template());
this.renderAll();
return this;
},
renderAll: function() {
var that = this;
this.collection.each(function(blog) {
that.renderItem(new BlogModelView({model: blog}));
});
},
renderItem: function(blog) {
this.$el.find('#blog-posts').append(blog.render(blog).el);
}
});
return BlogCollectionView;
});
Here is my require.config:
define(function() {
require.config({
hbs : {
templateExtension : 'hbs',
disableHelpers: true,
disableI18n : true
},
shim: {
'backbone': {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
},
bootstrap: {
deps: [ 'jquery' ]
},
DlHighlight: {
exports: 'DlHighlight'
},
'jqueryMockAjax': {
exports: '$.mockjax',
deps: ['jquery']
},
json2 : {
exports: "JSON"
},
'underscore': {
exports: '_'
}
},
paths: {
backbone: 'libs/backbone/backbone',
bootstrap: 'libs/bootstrap/dist/js/bootstrap',
DlHighlight: 'libs/hl/hl-all',
highlight: 'libs/highlightjs/highlight.pack',
jquery: 'libs/jquery/jquery',
jqueryMockAjax: 'libs/jquery-mockjax/jquery.mockjax',
markdown: 'libs/markdown/lib/markdown',
text: 'libs/text/text',
underscore: 'libs/underscore/underscore',
hbs: 'libs/hbs/hbs',
handlebars: 'libs/hbs/Handlebars',
i18nprecompile: 'libs/hbs/hbs/i18nprecompile',
json2 : 'libs/hbs/hbs/json2',
'app.templates': '../templates/'
}
});
});
Here is the strange behavior. In my initialize, when I hit the debugger, I have access to the markdown object that I have imported, BUT if I have try to use the markdown object, then it is always undefined. If I put markdown in the initialize or in one of the render methods, the markdown variable is undefined. It makes no sense, but is there some behavior that I dont understand about requirejs. Any ideas?
After reading the code of a bower installation of markdown-js, I found that what bower installs won't work with RequireJS as-is. Try adding this shim:
"markdown": {
exports: "markdown"
}
As to why were you able to get a value for markdown in the debugger without the shim, I believe you were getting it (perhaps without realizing it) from the global scope. Markdown-js installs itself into the global scope (window.markdown, which is then accessible as markdown if no other variable interferes with it) when it is loaded. This is speculation but it fits the facts.
You can require all of those modules in the define clause itself:
define([
'backbone',
'hbs!app.templates/blog.collection.view',
'views/blog.item.view',
'markdown'
], function (
Backbone,
blogCollectionTemplate,
BlogModelView,
markdown
) {
'use strict';
// do stuff
});
Also, what do you mean by "If I put markdown in the initialize or in one of the render methods"? Do you mean actually explicitly requiring markdown in initialize and render? Is there any reason to not just load markdown in the define clause as labeled above?
If you are explicitly requiring markdown in initialize or render, I am not sure why that would return undefined, but let me know if moving requirements to the define clause fixes your issue (or if you can't do that). Perhaps you could post the code in the markdown module (if it's not a library that is)?

Uncaught Error: No module: MyApp

I load AngularJs and jQuery using RequireJs in nodeJs framework.
That is main.js
require.config({
paths: {
angular: 'vendor/angular.min',
bootstrap: 'vendor/twitter/bootstrap',
jquery: 'vendor/jquery-1.9.0.min',
domReady: 'vendor/require/domReady',
underscore: 'vendor/underscore.min'
},
shim: {
angular: {
deps: [ 'jquery' ],
exports: 'angular'
}
}
});
require([
'app',
'angular-boot'
], function() {
});
in app.js
define(['angular'], function (angular) {
return angular.module('MyApp', []);
})
and in angular-boot.js
define([ 'angular', 'domReady' ], function (angular, domReady) {
domReady(function() {
angular.bootstrap(document, ['MyApp']);
});
});
In my html file I have only this line, in order to declare and use requirejs.
Not ng-ap or anything else.
<script data-main="js/main" src="js/require.js"></script>
The problem is that sometimes runs, sometimes not.
The error when it doesn't run is
Uncaught Error: No module: MyApp
If there is any thought about it, I would really appreciate it.
Thank you very much.
In your shim, you need to setup the app as a dependency to angular-boot. Your angular-boot file depends on app (where MyApp is defined), and because the load order for these two files is not specified, sometimes angular-boot loads before the app and thus produces that error.
To remedy, just update your shim as such:
shim: {
angular: {
deps: [ 'jquery' ],
exports: 'angular'
},
'angular-boot': {
deps: ['app']
}
}
and than, since you don't need to include the 'app' explicitly your require call can be reduced to:
require(['angular-boot']);

Correct way to set up Marionette Js with core AMD build?

I am learning Marionett on the side, and am trying to stick to the core amd build and not shim marionett. here's my require config:
require.config({
paths : {
backbone : 'lib/backbone',
underscore : 'lib/underscore',
jquery : 'lib/jquery',
marionette : 'lib/backbone.marionette',
'backbone.wreqr' : 'lib/backbone.wreqr',
'backbone.babysitter' : 'lib/backbone.babysitter',
hbs : 'lib/hbs',
Handlebars : 'lib/Handlebars'
},
shim : {
jquery : {
exports : 'jQuery'
},
underscore : {
exports : '_'
},
backbone : {
deps : ['jquery', 'underscore'],
exports : 'Backbone'
}
},
hbs: {
disableI18n: true,
disableHelpers: true
}
});
I am getting Backbone is undefined in the application module of marionette when I create an application module as follows:
define(["marionette", "views/CatCompositeView"], function (Marionette, CatCompositeView) {
var app = new Marionette.Application();
app.addRegions({
mainRegion: '#content'
});
app.addInitializer(function(options){
var catCompositeView = new CatCompositeView({
collection: options.cats
});
app.mainRegion.show(catCompositeView);
});
return app;
});
Any ideas? I am able to get it all working when shimming marionette so I'm ok for now, but would like to load it all individually.
UPDATE: Here's how I ended up doing this in my require config:
require.config({
paths : {
backbone : 'lib/backbone',
underscore : 'lib/underscore',
jquery : 'lib/jquery',
marionette : 'lib/backbone.marionette',
'backbone.wreqr' : 'lib/backbone.wreqr',
'backbone.babysitter' : 'lib/backbone.babysitter',
hbs : 'lib/hbs',
Handlebars : 'lib/Handlebars'
},
shim : {
jquery : {
exports : 'jQuery'
},
underscore : {
exports : '_'
},
backbone : {
deps : ['jquery', 'underscore'],
exports : 'Backbone'
},
'backbone.wreqr': {
deps : ['backbone']
},
'backbone.babysitter': {
deps : ['backbone']
}
},
hbs: {
disableI18n: true,
disableHelpers: true
}
});
You need to shim Backbone.Marionnette too:
marionette : {
deps: ["backbone", "underscore"],
exports: "Backbone.Marionette"
}
See update above. I needed to add backbone as a dependency for wreqr and babysitter to load them individually.

RequireJS optimizer with coffeescript

I'm running on severals issues when I'm trying to run the node RequireJS on my project.
This is my folder structure :
-root
-/src
-App.coffee
-/static
-/vendor
-/plugin
-r.js
-coffee-script.js
-/lib
-jquery.js
-main.js
-build.js
This is my build.js file :
({
appDir : './',
baseUrl : './static/js/',
dir : '../public',
optimize : 'uglify',
exclude : ['coffee-script'],
stubModules : ['cs'],
paths: {
// Libraries
'modernizr' : 'vendor/modernizr',
'jquery' : ['//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min', 'vendor/jquery'],
'jqueryui' : 'vendor/jquery-ui',
'backbone' : 'vendor/backbone',
'underscore' : 'vendor/underscore',
// Plugins
'plugin' : 'plugin/plugin',
// RequireJS
'cs' : 'plugin/cs',
'coffee-script' : 'plugin/coffee-script'
},
shim: {
'jqueryui' : ['jquery'],
'underscore': {
exports: '_'
},
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
},
modules: [{
name: "main"
}]
})
And finally this is my main.js file :
require({
baseUrl : '../../src/',
paths: {
cs: '../../cs',
'coffee-script': '../../coffee-script'
}
}, ['cs!App']);
I'm getting always error related to incorrect path setting and I can't figured out where I'm wrong.
Thanks !
The solution below worked in my case. It's a common issue with non-amd modules imported with shim or wrapped manually (for instance this one, with custom paths).
Try avoiding relative paths and use absolute 1 paths instead.
A dependency called from an aliased module will use its current location to find the required module.
require.config(
{
locale: window.GIS.i18n.locale,
deps: ['cs!modules/main'],
paths: {
'i18n' : 'i18n',
'underscore' : 'libs/underscore',
'cs' : 'libs/cs', // there's no '../something/else/libs/cs'
'CoffeeScript' : 'libs/coffeescript', // ibidem.
'text' : 'libs/text',
// ... other amd module aliases go here...
},
shim:{
// ...
}
});
define(['cs!modules/main'], function(){});
1 Of course, these are not absolute paths per se, but they are relative to the root of your module tree.

Categories

Resources