When adding a Backstack as a module for a test app in my router file it throws a error 404 loading backbone.js
I can't figure out what is the cause, but an extra http get is added that requests js/Backbone.js which then throws a 404 as I only have my libs in the js/libs folder.
What could be the issue?
// index.html
<!DOCTYPE html>
<html>
<head>
<title>Starting Require</title>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0"/>
<script data-main="js/main" src="js/libs/require.js"></script>
</head>
<body>
<div id="content">
</div>
</body>
// main.js
requirejs.config({
paths : {
'jquery' : 'libs/jquery-1.8.2.min',
'underscore' : 'libs/underscore',
'backbone' : 'libs/backbone',
'backstack' : 'https://github.com/pwalczyszyn/backstack/blob/master/backstack'
},
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'backstack': {
deps: ['backbone', 'underscore', 'jquery'],
},
'underscore': {
exports: '_'
}
}
});
require([
'app',
], function(App){
App.initialize();
});
// app.js
define([
'jquery',
'underscore',
'backbone',
'router'
], function($, _, Backbone, Router){
var initialize = function(){
Router.initialize();
};
return {
initialize: initialize
};
});
// router.js
define([
'jquery',
'underscore',
'backbone',
'backstack'
], function($, _, Backbone, Backstack) {
var AppRouter = Backbone.Router.extend({
routes: {
'': 'welcome'
}
});
var initialize = function(){
var app_router = new AppRouter;
app_router.on('route:welcome', function(){
$('#content').html('Hello World!');
});
};
return {
initialize: initialize
};
});
backstack uses the Backbone module name, not backbone.
This fiddle uses only a capitalised Backbone module name and has no extra module load.
http://jsfiddle.net/MUSBk/
Or else you could define an alias (omit the module name if you place in a file called Backbone.js) - http://jsfiddle.net/3UXGZ/1/
define('Backbone', ['backbone'], function (Backbone) {
return Backbone;
});
I'm not sure you can use your path config to point a new Backbone module to your existing Backbone JS, as this would probably load the same file as a second instance of Backbone, which might cause issues.
Related
In this plunk I have a sample code running Angular + Angular UI Router + RequireJS. There are two pages, each with a corresponding controller. If you click on View 1, you should see a page that contains a directive.
When the page loads it throws the following exception:
Cannot read property 'controller' of undefined at at my-ctrl-1.js:3
meaning that app is undefined in my-ctrl-1.js even though I'm returning it in app.js. What's wrong with this code?
HTML
<ul class="menu">
<li><a href ui-sref="view1">View 1</a></li>
<li><a href ui-sref="view2">View 2</a></li>
</ul>
<div ui-view></div>
main.js
require.config({
paths: {
'domReady': 'https://cdnjs.cloudflare.com/ajax/libs/require-domReady/2.0.1/domReady',
'angular': 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min',
"uiRouter": "https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router"
},
shim: {
'angular': {
exports: 'angular'
},
'uiRouter':{
deps: ['angular']
}
},
deps: [
'start'
]
});
start.js
define([
'require',
'angular',
'app',
'routes'
], function (require, angular) {
'use strict';
require(['domReady!'], function (document) {
angular.bootstrap(document, ['app']);
});
});
app.js
define([
'angular',
'uiRouter',
'my-ctrl-1',
'my-ctrl-2',
'my-dir-1'
], function (angular) {
'use strict';
console.log("app loaded");
return angular.module('app', ['ui.router']);
});
my-ctrl-1.js
define(['app'], function (app) {
'use strict';
app.controller('MyCtrl1', function ($scope) {
$scope.hello = "Hello1: ";
});
});
The problem is that you have a circular dependency between app.js and my-ctrl-1.js. When RequireJS encounters a circular dependency, the references it passes to the modules' factories are going to be undefined. There are many ways to solve the issue. One simple way that would work with the code you show could be to change my-ctrl-1.js to:
define(function () {
'use strict';
return function (app) {
app.controller('MyCtrl1', function ($scope) {
$scope.hello = "Hello1: ";
});
};
});
And in app.js:
define([
'angular',
'my-ctrl-1',
'my-ctrl-2',
'my-dir-1',
'uiRouter',
], function (angular, ctrl1) {
'use strict';
console.log("app loaded");
var app = angular.module('app', ['ui.router']);
ctrl1(app);
return app;
});
Presumably, you'll have to do the same thing with your other controler.
The documentation has a section on the topic of circular dependencies and other methods to handle them.
I am trying to create a very simple Angular + Require project template.
I am getting error-
Error: Script error for: ngRoute
http://requirejs.org/docs/errors.html#scripterror
In my index.html i have
require(
[
'jquery',
'angular',
'mainApp',
], function($, angular, mainApp) {
var AppRoot = angular.element(document.getElementById('CollectorWallApp'));
AppRoot.attr('ng-controller','MainController');
angular.bootstrap(AppRoot, ['MainApp']);
});
In mainApp.js i'm doing the following-
'use strict';
define(['angular','ngRoute'],function(angular,ngRoute){
var MainApp = angular.module('MainApp',['ngRoute']);
MainApp.controller("MainController", function ($scope) {
console.log("Main Controller working");
});
//Route configuration goes here
MainApp.config([ '$routeProvider', function ($routeProvider) {
console.log("--->checkiing out $routeProvider");
}]);
return MainApp;
});
In Require config
'paths': {
'angular': 'js/lib/angular/angular',
'ngRoute': 'js/lib/angular-route.min',
.
.
.
.
.
'shim': {
'angular': {
exports: 'angular',
},
'ngRoute': {
exports: 'ngRoute',
deps: ['angular']
},
Unable to debug or pin point the reason.
Note- all my require paths are correct. Kindly help. Thanks
I had my angularjs app setup in local and everything was working fine till I upload my code to the staging server. I now have issue with dependencies that are not respected but I can't see why. I guess it was working in local because it was loading the library faster. I now modified my app to try to fix this issue but can't manage to make it work.
My application is loading a single page app, composed of 3 views (main, map and map-data). I'm using AngularJS modules structure to launch this app. Here is my directory structure:
The index.html is pretty basic:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, minimum-scale=1.0" />
<title>Map Application</title>
<link rel="icon" sizes="16x16" href="/favicon.ico" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key={{ map_key }}&sensor=false"></script>
<script type="text/javascript" src="/js/bower_components/requirejs/require.js"></script>
<link rel="stylesheet" href="/css/main.css" media="screen" type="text/css">
<link rel="stylesheet" href="/js/bower_components/bootstrap/dist/css/bootstrap.css">
</head>
<body>
<!-- Content -->
<div id="content" data-ui-view></div>
<script>
// obtain requirejs config
require(['require', 'js/require-config'], function (require, config) {
// set cache beater
config.urlArgs = 'bust=v{{ version }}';
// update global require config
window.require.config(config);
// load app
require(['main']);
});
</script>
</body>
</html>
Then requirejs-config.js:
if (typeof define !== 'function') {
// to be able to require file from node
var define = require('amdefine')(module);
}
define({
baseUrl: 'js', // Relative to index
paths: {
'jquery': 'bower_components/jquery/dist/jquery.min',
'underscore': 'bower_components/underscore/underscore-min',
'domReady': 'bower_components/requirejs-domready/domReady',
'propertyParser': 'bower_components/requirejs-plugins/src/propertyParser',
'async': 'bower_components/requirejs-plugins/src/async',
'goog': 'bower_components/requirejs-plugins/src/goog',
'angular': 'bower_components/angular/angular',
'ngResource': 'bower_components/angular-resource/angular-resource',
'ui.router': 'bower_components/angular-ui-router/release/angular-ui-router',
'angular-google-maps': 'bower_components/angular-google-maps/dist/angular-google-maps',
'moment': 'bower_components/momentjs/moment',
'moment-timezone': 'bower_components/moment-timezone/moment-timezone',
'moment-duration-format': 'bower_components/moment-duration-format/lib/moment-duration-format'
},
shim: {
'angular': {
exports: 'angular'
},
'ngResource': ['angular'],
'ui.router' : ['angular']
}
});
Then the main.js:
/**
* bootstraps angular onto the window.document node
* NOTE: the ng-app attribute should not be on the index.html when using ng.bootstrap
*/
define([
'require',
'angular',
'./app'
], function (require, angular) {
'use strict';
/**
* place operations that need to initialize prior to app start here
* using the `run` function on the top-level module
*/
require(['domReady!'], function (document) {
angular.bootstrap(document, ['app']);
});
});
Then the app.js:
/**
* loads sub modules and wraps them up into the main module
* this should be used for top-level module definitions only
*/
define([
'angular',
'ui.router',
'./config',
'./modules/map/index'
], function (ng) {
'use strict';
return ng.module('app', [
'app.constants',
'app.map',
'ui.router'
]).config(['$urlRouterProvider', function ($urlRouterProvider) {
$urlRouterProvider.otherwise('/');
}]);
});
Here you can see that the app.js depends on the ./modules/map/index, where I'm loading all available controllers:
/**
* Loader, contains list of Controllers module components
*/
define([
'./controllers/mainCtrl',
'./controllers/mapCtrl',
'./controllers/mapDataCtrl'
], function(){});
Each controller are requesting the same kind of module, here is mapDataCtrl.js which is the one that is triggered by /:
/**
* Map Data controller definition
*
* #scope Controllers
*/
define(['./../module', 'moment'], function (controllers, moment) {
'use strict';
controllers.controller('MapDataController', ['$scope', 'MapService', function ($scope, MapService)
{
var now = moment();
$scope.data = {};
$scope.data.last_update = now.valueOf();
$scope.data.time_range = '<time range>';
$scope.data.times = [];
var point = $scope.$parent.map.center;
MapService.getStatsFromPosition(point.latitude, point.longitude).then(function(data){
$scope.data.times = data;
});
}]);
});
As you can see, the controller is requesting module.js where the states and module name are defined:
/**
* Attach controllers to this module
* if you get 'unknown {x}Provider' errors from angular, be sure they are
* properly referenced in one of the module dependencies in the array.
* below, you can see we bring in our services and constants modules
* which avails each controller of, for example, the `config` constants object.
**/
define([
'angular',
'ui.router',
'../../config',
'underscore',
'angular-google-maps',
'./services/MapService'
], function (ng) {
'use strict';
return ng.module('app.map', [
'app.constants',
'ui.router',
'angular-google-maps'
]).config(['$stateProvider', '$locationProvider', function ($stateProvider, $locationProvider) {
$stateProvider
.state('main', {
templateUrl: '/js/modules/map/views/main.html',
controller: 'MainController'
})
.state('main.map', {
templateUrl: '/js/modules/map/views/main.map.html',
controller: 'MapController',
resolve: {
presets: ['MapService', function(MapService){
return MapService.getPresets();
}],
courses: ['MapService', function(MapService){
return MapService.getCourses()
}]
}
})
.state('main.map.data', {
url: '/',
templateUrl: '/js/modules/map/views/main.map.data.html',
controller: 'MapDataController'
})
;
//$locationProvider.html5Mode(true);
}]);
});
It's in this file that I have an issue. I'm trying to load the module angular-google-maps because I need it in my MapCtr controller and most probably in MapDataCtrl. But I get the following message:
Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:modulerr] Failed to instantiate module app.map due to:
Error: [$injector:modulerr] Failed to instantiate module angular-google-maps due to:
Error: [$inj...<omitted>...1)
I have no idea what I am missing, for me everything looks tied correctly. What am I missing?
UPDATE 1
I think it's because angular-google-map is not AMD compliant, so I've modified my requirejs-config.js as follow:
if (typeof define !== 'function') {
// to be able to require file from node
var define = require('amdefine')(module);
}
define({
baseUrl: 'js', // Relative to index
paths: {
...
'underscore': 'bower_components/underscore/underscore-min',
'angular-google-maps': 'bower_components/angular-google-maps/dist/angular-google-maps',
...
},
shim: {
'angular': {
exports: 'angular'
},
'ngResource': ['angular'],
'ui.router' : ['angular'],
'angular-google-maps': {
deps: ["underscore"],
exports: 'angular-google-maps'
}
}
});
but I still have the same issue.
We can use an js library with require.js.There is no need to remove require.js. I still need to check why require.js config not working.
Meanwhile you can try this way.
// requirejs-config.js
define({
baseUrl: 'js', // Relative to index
paths: {
'jquery': 'bower_components/jquery/dist/jquery.min',
'underscore': 'bower_components/underscore/underscore-min',
'domReady': 'bower_components/requirejs-domready/domReady',
'propertyParser': 'bower_components/requirejs-plugins/src/propertyParser',
'async': 'bower_components/requirejs-plugins/src/async',
'goog': 'bower_components/requirejs-plugins/src/goog',
'angular': 'bower_components/angular/angular',
'ngResource': 'bower_components/angular-resource/angular-resource',
'ui.router': 'bower_components/angular-ui-router/release/angular-ui-router',
'angular-google-maps': 'bower_components/angular-google-maps/dist/angular-google-maps',
'moment': 'bower_components/momentjs/moment',
'moment-timezone': 'bower_components/moment-timezone/moment-timezone'
},
shim: {
'angular': {
exports: 'angular'
},
'ngResource': ['angular'],
'ui.router' : ['angular']
}
});
// google-map.js
define(['underscore', 'angular-google-maps'], function(){
});
And then requiring the module each time I need the map:
require(['google-map'], function(){
});
https://github.com/angular-ui/angular-google-maps/issues/390
I am trying to use the requirejs-hbs lib in a Backbone project. I have the Handlebars lib and the requirejs-hbs lib in the same folder. They are declared the same in my config. When I look at the sources in my chrome tab, I am only getting the require-hbs script, I am not getting the handlebars script. Here is my config file:
require.config({
hbs: {
templateExtension: '.hbs'
},
paths: {
backbone: "libs/backbone/backbone",
Handlebars: 'libs/handlebars/handlebars.amd',
hbs: 'libs/requirejs-hbs/hbs',
jquery: 'libs/jquery/jquery',
underscore: 'libs/underscore/underscore'
},
shim: {
backbone: {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
},
underscore: {
exports: '_'
}
}
});
require(['js/router/easier.view'], function(View) {
'use strict';
var view = new View();
});
And here is the view where I am trying to access my template.
define(function(require) {
'use strict';
var Backbone = require('backbone');
var testTemplate = require('hbs!views/test.hbs');
var router = Backbone.View.extend({
render: function() {
debugger;
}
});
return router;
});
The error I get is GET http://localhost:9000/handlebars.js 404 (Not Found). I have the other files that I am declaring, but I do not have the handlebars.js. What am I doing wrong?
You are creating a path to Handlebars but if you look at the source of requirejs-hbs you see that it uses handlebars.
So either change the requirejs-hbs source to Handlebars or change your path to handlebars.
Should work.
I have problems loading this libraries with the shim option in RequireJS (maybe, because my poor background on that library). I try to look in documentation and see some other pages but the problem persist.
This is my app folder structure:
index.html
js/main.js
js/app/router.js
js/app/app.js
js/views/homeview.js
js/libs/backbone/backbone-1.0.0.js
js/libs/underscore/underscore-1.5.1.js
js/libs/jquery/jquery-1.10.2.js
js/libs/require/require-2.1.8.js
All start in index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="width=device-width, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>App</title>
</head>
<body>
<div class="page">
Loading...
</div>
<script data-main="js/main" src="js/libs/require/require-2.1.8.js"></script>
</body>
</html>
That loads main.js
require.config({
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
},
paths: {
app: 'app',
mod: 'app/mods',
backbone: 'libs/backbone/backbone-1.0.0',
underscore: 'libs/underscore/underscore-1.5.1',
jquery: 'libs/jquery/jquery-1.10.2',
},
});
require([
'app/app',
], function (App) {
App.initialize();
});
That defines the paths to the libraries and the shim options for non-AMD libraries.
Then comes app.js
define([
'app/router',
], function(Router) {
var initialize = function() {
//var router = new Router();
//router.initialize();
Router.initialize();
};
return {
initialize: initialize,
};
});
Then router.js:
define([
'jquery',
'underscore',
'backbone',
'app/views/homeview',
], function($, _, Backbone, HomeView) {
var AppRouter = Backbone.Router.extend({
routes: {
'': 'home',
}
});
var initialize = function() {
var appRouter = new AppRouter();
var homeView = new HomeView();
appRouter.on('route:home', function() {
userListView.render();
console.log('We have loaded the home page.');
});
Backbone.history.start();
};
return {
initialize: initialize,
};
});
Now here i have a problem beacause looking at the network tab in the chrome developer tools only jquery loads, nor backbone or underscore.
Then, and finally, because it's defined a reference to a view, loads homeview.js
define([
'jquery',
'underscore',
'backbone',
'libs/text!app/tpl/home.html',
], function($, _, Backbone, HomeTpl) {
var homeView = Backbone.View.extend({
el: '.page',
render: function() {
//var self = this;
//users.fetch({
// success: function() {
var template = _.template(HomeTpl, {});
//self.$el.html(template);
this.$el.html(template);
// }
//});
},
});
return homeView;
});
And the problem, because at line var homeView = Backbone.View.extend({ shows the error: "Uncaught TypeError: Cannot read property 'View' of undefined", but i think that's because backbone never loads.
¿Can anyone tell what i'm doing terribly wrong? I looking the code and several pages all day and i cannot figure it out the answer. Thanks in advance and apoliges for the long question, buy i've seen many people having this same issue and maybe the answer could help others too.
Can't find anything wrong, but you don't need to load the app modules in the paths
paths: {
app: 'app', // remove