Problem
When executing the compiled handlebars templates the global Handlebars object isn't exported. NOTE: the global Backbone object is working.
See, when the code App.templates.todos attempts to execute in the todos.js file it fails because App.templates.todos isn't defined. Well ultimately that's because the third line in the templates.js file can't execute because the global Handlebars object isn't defined.
Why wouldn't that object get defined? What did I do wrong with require.js here?
UPDATE: I've verified that the handlebars.runtime.js file is in fact executing before the templates.js file and so require.js is running them in the right order when loading the todos.js file.
Bower Components
{
"name": "todomvc-backbone-requirejs",
"version": "0.0.0",
"dependencies": {
"backbone": "~1.1.0",
"underscore": "~1.5.0",
"jquery": "~2.0.0",
"todomvc-common": "~0.3.0",
"backbone.localStorage": "~1.1.0",
"requirejs": "~2.1.5",
"requirejs-text": "~2.0.5",
"handlebars": "~2.0.0"
},
"resolutions": {
"backbone": "~1.1.0"
}
}
main.js
/*global require*/
'use strict';
// Require.js allows us to configure shortcut alias
require.config({
// The shim config allows us to configure dependencies for
// scripts that do not call define() to register a module
shim: {
backbone: {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
},
backboneLocalstorage: {
deps: ['backbone'],
exports: 'Store'
},
handlebars: {
exports: 'Handlebars'
},
templates: {
deps: ['handlebars'],
exports: 'App'
},
underscore: {
exports: '_'
}
},
paths: {
jquery: '../bower_components/jquery/jquery',
underscore: '../bower_components/underscore/underscore',
backbone: '../bower_components/backbone/backbone',
backboneLocalstorage: '../bower_components/backbone.localStorage/backbone.localStorage',
handlebars: '../bower_components/handlebars/handlebars.runtime',
templates: '../../../templates',
text: '../bower_components/requirejs-text/text'
}
});
require([
'backbone',
'views/app',
'routers/router'
], function (Backbone, AppView, Workspace) {
/*jshint nonew:false*/
// Initialize routing and start Backbone.history()
new Workspace();
Backbone.history.start();
// Initialize the application view
new AppView();
});
todos.js
/*global define*/
define([
'jquery',
'backbone',
'handlebars',
'templates',
'common'
], function ($, Backbone, Handlebars, Templates, Common) {
'use strict';
var TodoView = Backbone.View.extend({
tagName: 'li',
template: App.templates.todos,
...
});
return TodoView;
});
templates.js
this["App"] = this["App"] || {};
this["App"]["templates"] = this["App"]["templates"] || {};
this["App"]["templates"]["stats"] = Handlebars.template({"1":function(depth0,helpers,partials,data) {
From official documentation of RequireJS:
The shim config only sets up code relationships. To load modules that
are part of or use shim config, a normal require/define call is
needed. Setting shim by itself does not trigger code to load.
So first you need to somehow call the Handlebars and after try to use it in templates.js.
Related
I'm loading my dependencies with require.js and I'm getting this error:
backboneforce.js:5 Uncaught SyntaxError: Unexpected token <
My Config file:
require.config({
// Require is defined in /scripts, so just the remaining path (and no ext needed)
'baseUrl': 'js/',
'paths': {
"jquery": "libs/jquery",
"underscore": "libs/underscore",
"backbone": "libs/backbone",
"bootstrap": "libs/bootstrap",
"text": "libs/text",
"notify": "libs/notify",
"backboneForce":"libs/backboneforce",
"forceTK":"libs/forcetk/forcetk",
"forceTKUI":"libs/forcetk/forcetkui"
},
'shim': {
bootstrap: {
deps: ['jquery'],
exports: 'Bootstrap'
},
backbone: {
'deps': ['jquery', 'underscore'],
'exports': 'Backbone'
},
underscore: {
'exports': '_'
},
forceTK:{
deps:['jquery'],
exports:'forcetk'
}
}
});
require([
// Load our app module and pass it to our definition function
'app'
], function (App) {
// The "app" dependency is passed in as "App"
App.initialize();
});
and here is my app.js:
define([
'jquery',
'underscore',
'backbone',
'bootstrap',
'backboneForce',
'forceTK',
'forceTKUI',
'notify',
'router/navigationRouter'
], function ($, _, Backbone, bootstrap, bbforce, forcetk, forcetkui, notify, Router) {
var initialize = function () {
Router.initialize();
console.log(bbforce);
}
return {
initialize: initialize
};
});
In my browser network tab, all dependencies are loaded, but I'm getting this error for forceTK, forceTKUI and backboneForce.
It looks like the path to the backboneforce file is wrong and the server is returning a 404 HTML page.
The following line:
"backboneForce":"libs/backboneforce",
should probably be
"backboneForce":"libs/backboneforce/backboneforce", // or backbone.force
How does require paths work?
Paths inside the paths option are just aliases. If you want to point to a module, you must include the file name without the extension.
If you have the following directory structure:
lib
├───backboneforce
│ └───backbone.force.js
The path should be lib/backboneforce/backbone.force.
Where is the < coming from?
When you make a request with a path to a non-existent file, the server will often return some sort of default 404 error message or it will redirect to a default page (like the home page).
Here's what Stack Overflow returns:
The < comes from <!DOCTYPE html> on the first line of the response, which the browser tries to interpret as JavaScript.
I'm using Handlebars with Require.js, but for some reasons, Handlebars is undifined.
My config:
require.config({
paths: {
underscore: "lib/underscore-min", //1.8.3
backbone: "lib/backbone-min", //1.2.3
jquery: "lib/jquery-2.1.4.min", //2.1.4
marionette: "lib/backbone.marionette.min", //2.4.3
handlebars: "lib/handlebars.runtime.amd.min", //4.0.5
shim: {
"underscore": {
exports: "_"
},
"backbone": {
deps: ["underscore", "jquery"],
exports: "Backbone"
},
"jquery": {
exports: "jquery"
},
"marionette": {
deps: ["backbone", "jquery"],
exports: "Marionette"
},
"handlebars":{
exports: "Handlebars"
}
}
});
...and than in the same file:
require(["handlebars"], function(Handlebars){
"use strict";
console.log(Handlebars); //undefined
});
In an other file:
define(["handlebars"], function(Handlebars){
"use strict";
console.log(Handlebars); //still undefined
});
I'm also using precompiled templates, which are working perfectly fine, so I have no idea, what could be the problem.
Thanks in advance!
---- SOLUTION ----
As Rajab pointed out, the problem was that I used "handlebars" instead of "handlebars.runtime" so thanks for his help!
You need to use:
require(["handlebars.runtime"], function(Handlebars){`
instead of
require(["handlebars"], function(Handlebars){`
and also shim is used only for modules that don't support AMD. Shim completely useless in your example. All these libraries support AMD. For example look at 16 line in backbone.js:
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
or line 1002 in handlebars.runtime.amd.js
define('handlebars.runtime', ['exports', 'module', './handlebars/base' ... etc
All dependencies already inside it. So you need only paths in config:
require.config({
paths: {
underscore: "lib/underscore-min",
backbone: "lib/backbone-min",
jquery: "lib/jquery-2.1.4.min",
marionette: "lib/backbone.marionette.min",
handlebars: "lib/handlebars.runtime.amd.min",
}
}
require(['handlebars.runtime'], function(HandlebarsOrWhateverNameYouWantItStillWillbeHandlebars){
"use strict";
console.log(HandlebarsOrWhateverNameYouWantItStillWillbeHandlebars);
});
that's all.
I want to create Backbone.js app with Require.js.
But I have an error in console: Uncaught Error: Module name "underscore" has not been loaded yet for context: _. Use require([])
require.config({
baseUrl: 'js/',
paths : {
'jquery' : 'jquery',
'underscore' : 'underscore',
'backbone' : 'backbone',
shim: {
'underscore': {
exports: '_'
},
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
}
}
});
define('app', ['jquery','backbone', 'underscore'], function ($, Backbone, _){
var Model = Backbone.model.extend({});
var model = new Model;
});
require(['app','jquery', 'backbone', 'underscore']);
How I can resolve this problem?
You still need to list underscore as a part of paths so you can refer to it in the shims. Also, not sure what your directory structure looks like, but I'm writing this with the assumption that library code is in the /js/libs directory). Finally, note you won't need to require any of the dependencies of app -- the joy of RequireJS is that it'll figure out what to load.
So...
require.config({
baseUrl: 'js/',
paths : {
'jquery' : 'lib/jquery',
'underscore' : 'lib/underscore',
'backbone' : 'lib/backbone',
},
shim: {
'underscore': {
exports: '_'
},
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
}
});
define('app', ['jquery','backbone', 'underscore'], function ($, Backbone, _){
var Model = Backbone.Model.extend({});
var model = new Model({
foo: 'bar'
});
var app = {
model: model
};
// ...
return app;
});
require(['app'], function(App) {
App.model.get('foo'); // <<=== returns 'bar'
});
The shim is mentioned inside the paths object. I am not sure if that is the problem, but wanted to mention that here.
You need Underscore.js as listed in your require statement.
I've started a new backbone, marionette and require project using version 2.2 (i previously worked with 1.8) It seems a lot has changed. I'm getting an error when the browser loads marionette:
Uncaught TypeError: Cannot read property 'ChildViewContainer' of undefined
This is my main.js file:
require.config({
baseURL: 'scripts',
paths: {
"jquery": "lib/jquery",
"underscore": "lib/underscore",
"backbone": "lib/backbone",
"marionette": 'lib/backbone.marionette',
"templates": "../templates",
"text": "lib/text"
},
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
marionette: {
deps: ['jquery', 'underscore', 'backbone'],
exports: 'Marionette'
},
waitSeconds: 15
}
});
require([ "app", "marionette"], function(App, marionette) {
App.start();
});
And this is my app.js file:
define(["marionette", "router"], function (Marionette, AppRouter) {
var MyApp = Marionette.Application.extend({
initialize: function(options) {
console.log("options.container");
}
});
var MyApp = new MyApp({container: '#page'});
MyApp.addInitializer(function (options) {
MyApp.Router = new AppRouter();
Backbone.history.start();
});
// export the app from this module
return MyApp;
});
Just look at your backbone.js file. It's empty. Download backbone.js from http://backbonejs.org/ and replace it.
I just ran into this same issue myself. The issue was multiple instances of Marionette being included on the page. (i had errantly placed a script tag for marionette on the page from cdnjs, as well as trying to include the static file locally via require). removing the reference to the external JS file helped me...
I can't seem to figure out how to load Bootstrap via RequireJS. None of the examples that I found worked for me.
Here is my shim:
require.config({
// Sets the js folder as the base directory for all future relative paths
baseUrl: "./js",
urlArgs: "bust=" + (new Date()).getTime(),
waitSeconds: 200,
// 3rd party script alias names (Easier to type "jquery" than "libss/jquery, etc")
// probably a good idea to keep version numbers in the file names for updates checking
paths: {
// Core libsraries
// --------------
"jquery": "libs/jquery",
"underscore": "libs/lodash",
"backbone": "libs/backbone",
"marionette": "libs/backbone.marionette",
// Plugins
// -------
"bootstrap": "libs/plugins/bootstrap",
"text": "libs/plugins/text",
"responsiveSlides": "libs/plugins/responsiveslides.min",
'googlemaps': 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDdqRFLz6trV6FkyjTuEm2k-Q2-MjZOByM&sensor=false',
// Application Folders
// -------------------
"collections": "app/collections",
"models": "app/models",
"routers": "app/routers",
"templates": "app/templates",
"views": "app/views",
"layouts": "app/layouts",
"configs": "app/config"
},
// Sets the configuration for your third party scripts that are not AMD compatible
shim: {
"responsiveSlides": ["jquery"],
"bootstrap": ["jquery"],
"backbone": {
// Depends on underscore/lodash and jQuery
"deps": ["underscore", "jquery"],
// Exports the global window.Backbone object
"exports": "Backbone"
},
"marionette": {
// Depends on underscore/lodash and jQuery
"deps": ["backbone", "underscore", "jquery"],
// Exports the global window.Backbone object
"exports": "Marionette"
},
'googlemaps': { 'exports': 'GoogleMaps' },
// Backbone.validateAll plugin that depends on Backbone
"backbone.validate": ["backbone"]
},
enforceDefine: true
});
and here is how I call Bootstrap:
define([
"jquery",
"underscore",
"backbone",
"marionette",
"collections/Navigations",
'bootstrap',
],
function($, _, Backbone, Marionette, Navigations, Bootstrap){
The error that I get is this:
Uncaught Error: No define call for bootstrap
Any ideas on how to get this resolved?
I found a working example here:
https://github.com/sudo-cm/requirejs-bootstrap-demo
I followed it to get my code to work.
According to that demo, especially app.js, you simply make a shim to catch Bootstrap's dependency on jQuery,
requirejs.config({
// pathsオプションの設定。"module/name": "path"を指定します。拡張子(.js)は指定しません。
paths: {
"jquery": "lib/jquery-1.8.3.min",
"jquery.bootstrap": "lib/bootstrap.min"
},
// shimオプションの設定。モジュール間の依存関係を定義します。
shim: {
"jquery.bootstrap": {
// jQueryに依存するのでpathsで設定した"module/name"を指定します。
deps: ["jquery"]
}
}
});
and then mark Bootstrap as a dependency of the app itself, so that it loads before app.js.
// require(["module/name", ...], function(params){ ... });
require(["jquery", "jquery.bootstrap"], function ($) {
$('#myModalButton').show();
});
Finally, since app.js is the data-main,
<script type="text/javascript" src="./assets/js/require.min.js" data-main="./assets/js/app.js"></script>
Bootstrap's JS is guaranteed to load before any application code.
Bootstrap lib does not return any object like jQuery, Underscore or Backbone: this script just modifies the jQuery object with the addition of new methods. So, if you want to use the Bootstrap library, you just have to add in the modules and use the jquery method as usual (without declarating Bootstrap like param, because the value is undefined):
define([
"jquery",
"underscore",
"backbone",
"marionette",
"collections/Navigations",
"bootstrap",
],
function($,_,Backbone,Marionette,Navigations){
$("#blabla").modal("show"); //Show a modal using Bootstrap, for instance
});
I found it was sufficient to add the following to my requirejs.config call (pseudocode):
requirejs.config({
...
shim: {
'bootstrap': {
deps: ['jquery']
}
}
});
I like to use Require.Js ORDER plugin, what it does? Simply loads all your Libraries in order, in this case you won't get any errors, ohh and bootstrap depends on jQuery, so we need to use shim in this case:
requirejs.config({
baseUrl: "./assets",
paths: {
order: '//requirejs.org/docs/release/1.0.5/minified/order',
jquery: 'http://code.jquery.com/jquery-2.1.0.min',
bootstrap: '//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min'
},
shim: {
'bootstrap': {
deps:['jquery']
}
}
});
require(['order!jquery', 'order!bootstrap'], function($) {
});