Using require js getting undefined for all modules other than jquery - javascript

My jQuery library is getting loaded, but I'm getting an undefined error for any other modules I'm importing. Most of them have a jQuery dependency, which I shim in. Can anyone tell me why all my other modules are undefined?
requirejs.config({
baseUrl: 'js',
shim: {
'jqueryui': ['jquery'],
'dynatree': ['jquery'],
'noty' : ['jquery']
},
paths: {
jquery: 'vendor/jquery',
jqueryui: 'vendor/jqueryui',
dynatree: '../includes/dynatree/jquery.dynatree.min',
jsPlumb: '../includes/jsPlumb/dist/js/jquery.jsPlumb-1.5.5-min',
noty: '../includes/noty/packaged/jquery.noty.packaged.min'
}
});
requirejs(['jquery', 'jqueryui', 'dynatree', 'jsPlumb', 'noty'],
function ( $, jqueryui, dynatree, jsPlumb, noty ) {
console.log('hello', $, noty, jsPlumb, dynatree);
});

jquery ui doesn't export anything, it uses the same jquery symbol. I'd say the same applies for the rest of the libraries.
Even in the case they'd export something, it won't work because you're not setting the export symbol for your shims. Here you have an example of a shim with export
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
//Once loaded, use the global 'Backbone' as the module value.
exports: 'Backbone'
},
}
I'd replace your code by
requirejs(['jquery', 'jqueryui', 'dynatree', 'jsPlumb', 'noty'],
function ($) { // $ is the only symbol that needs to be used
});

Related

Handlebars is undefined using Require.js

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.

Require JS, Loading Libraries through CDN fails

I have read the answer to this question require js loading scripts from cdn fail. But in my case it does not help. I have a require JS setup and I want to use CDN to load my libraries.
The Require JS documentation says below is the right way to load libs from CDN with a fallback to local files.
requirejs.config({
//To get timely, correct error triggers in IE, force a define/shim exports check.
enforceDefine: true,
paths: {
jquery: [
'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min',
//If the CDN location fails, load from this location
'lib/jquery'
]
}
});
require(['jquery'], function ($) {
});
I am using the same method but I get an error instead, below is my code
requirejs.config({
baseUrl: location.protocol + '//' + location.host + '/app',
waitSeconds: 0,
paths: {
'jquery': ['https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min','/assets/js/vendor/jquery'],
'jqueryPjax': '/assets/js/vendor/jquery.pjax',
'jqueryUI': '/assets/js/vendor/jquery-ui.min',
'jqueryMousewheel': '/assets/js/jquery.mousewheel',
'jScrollPane': '/assets/js/jquery.jscrollpane.min',
'fastclick': '/assets/js/vendor/fastclick',
'jquerySlidebars': '/assets/js/jquery.slidebars.min',
'imagesLoaded': '/assets/js/imagesloaded.pkgd.min',
'fancyBox': '/assets/js/jquery.fancybox.pack',
'fancyBoxThumb': '/assets/js/jquery.fancybox-thumbs',
'text': '/assets/js/vendor/text',
'chosen': '/assets/js/vendor/chosen',
'bb': '/assets/js/vendor/backbone-min',
'underscore': '/assets/js/vendor/underscore-min',
'angular': '/assets/js/angular.min',
'ventFactory': 'base/ventFactory',
'util': 'base/util',
'dom': 'base/dom',
'actionHandler': 'base/actionHandler',
'ajax': 'base/ajax'
},
shim: {
'jquery': {
exports: 'jQuery'
},
'jqueryUI': {
deps: ['jquery']
},
'angular': {
exports: 'angular'
},
'jqueryPjax': {
deps: ['jquery'],
exports: 'jQuery.fn.pjax'
},
'jqueryMousewheel': {
deps: ['jquery'],
exports: 'jQuery.fn.mousewheel'
},
'jScrollPane': {
deps: ['jqueryMousewheel'],
exports: 'jQuery.fn.jScrollPane'
},
'jquerySlidebars': {
deps: ['jquery'],
exports: 'jquerySlidebars'
},
'fancyBox': {
deps: ['jquery'],
exports: 'fancyBox'
},
'fancyBoxThumb': {
deps: ['jquery', 'fancyBox'],
exports: 'fancyBoxThumb'
},
'chosen': {
deps: ['jquery'],
exports: 'chosen'
}
}
});
requirejs(['jquery', 'app'], function($, app) {
$(function() {
app.start();
});
});
I have just made the changes for Jquery as of now and I am giving both CDN URL and local path but when I load my page I get an error
TypeError: $el.siblings is not a function
Adding on
I am using Require JS for loading my libs but then at the production I am using almond, which combines all modules into one single file, so has this something to do with the error ?
Any help on this is highly appreciated. Thanks
Adding on I am using Require JS for loading my libs but then at the production I am using almond, which combines all modules into one single file, so has this something to do with the error ?
Yes, it does. Almond cannot do dynamic loading. In other words, everything you want Almond to load must be into a single bundle of modules. You cannot use a CDN with Almond.
"No dynamic loading" is the first restriction in its list of restrictions.

Can't load Bootstrap with RequireJS

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($) {
});

How to mixin Underscore plugins in RequireJS?

What is the right way to execute code on Underscore when it gets loaded? I am trying to execute the below code to extend the _ exported namespace automatically when modules require it:
_.mixin(_.str.exports());
The docs are a bit vague but I think I put it in the shim init section? I tried the below but I can't even get a breakpoint to hit in the init:
require.config({
paths: {
jquery: 'libs/jquery/jquery.min',
underscore: 'libs/underscore/lodash.min',
underscorestring: 'libs/underscore/underscore.string.min'
},
shim: {
underscore: {
exports: '_'
}
underscorestring: {
deps: ['underscore'],
init: function (_) {
//Mixin plugin to namespace
_.mixin(_.str.exports());
return _;
}
}
}
});
When I try to do this and use underscorestring, I get this error:
Uncaught TypeError: Object function s(e){return new o(e)} has no
method 'startsWith'
Docs:
http://requirejs.org/docs/api.html#config-shim
http://requirejs.org/docs/api.html#config-callback
I don't know if it's the correct way, but I got it working by inverting things so that underscore depends on underscore.string. Also, this way you don't have to require underscore.string.
require.config({
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'underscore': {
deps: ['underscore.string'],
exports: '_',
init: function(UnderscoreString) {
_.mixin(UnderscoreString);
}
}
},
paths: {
'backbone' : 'lib/backbone',
'jquery' : 'lib/jquery/jquery',
'text' : 'lib/require/text',
'underscore' : 'lib/underscore',
'underscore.string' : 'lib/underscore.string'
}
});
.
Update: 3/14/2014
Underscore.js v1.6.0 brought back AMD compatibility and init() has been removed from RequireJS, so some refactoring is in order. To continue getting Underscore preloaded with Underscore.string I made a mixer module to pull them together.
New Require.js config
requirejs.config({
paths: {
'backbone' : '../lib/backbone/backbone',
'backbone.base' : '../lib/backbone/backbone.base',
'backbone.extensions' : '../lib/backbone/backbone.extensions',
'jquery' : '../lib/jquery/jquery',
'text' : '../lib/require/text',
'underscore' : '../lib/underscore/underscore',
'underscore.mixed' : '../lib/underscore/underscore.mixed',
'underscore.string' : '../lib/underscore/underscore.string'
},
shim: {
'backbone.base': {
deps: ['underscore.mixed', 'jquery'],
exports: 'Backbone'
},
}
});
underscore.mixed
define([
'underscore',
'underscore.string'
], function(_, _s) {
_.mixin(_s.exports());
return _;
});
The final step is to replace all instances of 'underscore' with 'underscore.mixed' in module definitions. I attempted moving Underscore into a file named underscore.base.js and making the regular underscore the mixer (like the Backbone setup) to avoid this step. Underscore, being a named module, disagreed with the plan.
Do you require underscorestring somewhere? Because if it isn't required, it won't be loaded.
I managed to get it working with almost exactly the same code you posted:
require.config({
paths: {
underscore: [
'//raw.github.com/documentcloud/underscore/master/underscore-min'
, 'lib/underscore'
]
, underscorestring: 'https://raw.github.com/epeli/underscore.string/master/dist/underscore.string.min'
}
, shim: {
underscore: { exports: '_' },
underscorestring: {
deps: ['underscore'],
init: function(_) {
_.mixin(_.str.exports());
return _; // guess, this is not needed.
}
}
}
, exclude: ['underscore']
});
require(['underscore', 'underscorestring'], function(_) {
console.log( _.chars("i'm a happy string.") );
});
Battling with this for hours before i understand what i was doing wrong
This is what i did wrong
You should not rename the file underscore.string in main.js
even though in my library i did rename the file in paths i name it back to 'underscore.string'
This is how your main.js should look like
require.config({
paths: {
underscore: 'lib/underscore',
'underscore.string' : 'lib/_string' ,
},
shim: {
underscore: {
exports: '_',
deps: [ 'jquery', 'jqueryui' ]
},
'underscore.string': {
deps: [ 'underscore' ]
},
}
....
You could then either add it as dependency with in your shim like i did for my mixin file
shim: {
mixin : {
deps: [ 'jquery', 'underscore', 'underscore.string' , 'bootstrap' ]
},
Or just define it in your different pages like
/*global define */
define([
'underscore.string'
], function ( ) {
it just work now you can access it through _.str or _.string
This is why you should do it this way and not try to name it something else
on line 663 of underscore.string.js
// Register as a named module with AMD.
if (typeof define === 'function' && define.amd)
define('underscore.string', [], function(){ return _s; });
Which means that it will only register it with AMD require JS if you are defining 'underscore.string'
For Mix in you could just with define
/*global define */
define([
'underscore',
'underscore.string'
], function ( ) {
_.mixin(_.str.exports());

problems with backbone.js and require.js in iOS webviews

I'm having some strange issues with our application not executing javascript
I have a web view thats loaded in an iPad app.
the page renders using require and backbone but something prevents the external libraries to execute.
the issues are with both d3.js and a jquery countdown plugin.
using firebug I dont get any errors but the countdown isnt starting.
same with d3 drawing some things but click functionality isnt working
im not sure if its a require issue or an iOS6 issue.
if it was a require issue i assume we'd get errors. but we dont.
anyone have any clues to what might be the issue?
main controller looks like this
/*global require: false */
/*jslint nomen: true */
// Sets up common libraries for all pages
require.config({
paths: {
// Major libraries
'jquery': 'lib/jquery-1.8.2.min',
//'jquery.mobile': 'lib/jquery.mobile-1.2.0.min',
//'jquery.mobile-config': 'lib/jquery.mobile-config',
'underscore': 'lib/underscore-min',
'backbone': 'lib/backbone-min',
'fastclick': 'lib/fastclick.min',
'easing': 'lib/jquery.easing.1.3',
'countdown':'lib/jquery.countdown.min',
// Require.js plugins
'text': 'lib/text',
'socket.io': 'lib/socket.io.min'
},
shim: {
'jquery': {
exports: '$',
exports: 'jQuery'
},
'easing': ['jquery'],
//'jquery.mobile-config': ['jquery'],
//'jquery.mobile': ['jquery','jquery.mobile-config'],
'fastclick': {
exports: 'FastClick'
},
'countdown': {
deps: ['jquery'],
exports: 'countdown'
},
'underscore': {
exports: '_'
},
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'socket.io': {
exports: 'io'
}
}
});
require(['jquery', 'underscore', 'views/main-view', 'view-controller','fastclick', 'easing', 'countdown'], function ($, _, MainView, ViewController, fc, easing, countdown) {
"use strict";
var mainView = new MainView();
$("body").html(mainView.render().el);
ViewController.initialize();
});

Categories

Resources