What is the purpose of "define.amd = {jQuery: true }" in the code of RequireJS? - requirejs

Can any one explain with details, why in the require.js file the following code is set:
define.amd = {
jQuery: true
};
Reference Link: Default set to jquery as true

Setting define.amd to some value is done to help distinguish the define function provided by an AMD loader from any old define provided by something else. A typical pattern for code that should handle multiple loading scenarios is this:
if (typeof define === 'function' && define.amd) {
define(['exports'], factory(exports));
} else if (typeof module === 'object' && module.exports) {
factory(module.exports);
} else {
factory(exports);
}
The first line checks whether you have an AMD loader available, and will use the AMD loader if present. If a define function exists but it does not have the amd property set, then it is some random foreign define.
The name define is pretty generic. If it were not for the amd property, it would be sometimes difficult to determine whether the define that is present is really the one we care about.
Setting it to { jQuery: true } is a historical artifact. There's a pull request to jQuery that explains it. The author of the request is the author of RequireJS. In brief, the goal there was to indicate that the AMD loader is able to handle the case where multiple versions of jQuery call define. jQuery would call define only if define.amd.jQuery was truthy. It's probably been used by a few versions of jQuery in the past but newer versions no longer use this flag so it is still present mainly for supporting older jQuery versions.

Related

Why do I need to add a "shim" for AngularJS when using Require.js?

I have seen several examples that use this:
main.js
/*global require*/
'use strict';
require.config({
paths: {
angular: './angular',
app: './Content/app',
ngAnimate: './Scripts/angular-animate',
uiRouter: './Scripts/angular-ui-router'
},
shim: {
angular: {
exports: 'angular'
}
}
});
require(['angular', 'app'], function (angular) {
angular.bootstrap(document, ['app']);
});
Can someone explain to me why the shim is needed? My application uses other modules such as angular-ui router, jQuery etc. Do I need to do something similar and add a shim for these?
The rule is pretty simple: if a library/script/package/plugin is AMD-aware, then you don't need a shim. (Actually, you must not use a shim for it.) If it is not AMD-aware, then you need a shim.
A library/etc is AMD-aware if it detects that an AMD loader is present and calls define to make itself known to the loader.
jQuery from about 1.8 onwards has not needed a shim because it calls define. Angular, on the other hand, does not call define.
To know whether a specific piece of code needs a shim, you can read its documentation or if the documentation is not clear on this, then you can check the source code for a call to define. For instance jQuery 1.11.0 has this code:
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
How it looks like will vary from one case to the other but the basic think you want to look for is the check that define exists, is a function, has the amd property set and the call to define.
(Note that jQuery is a special case where they decided to hard code the name of the module in the define call (first parameter: jquery). Generally the name of the module won't be present in the define call but will be left for RequireJS to infer on the basis of the file name.)

What's the use of 'Buffer.isBuffer' when you could use 'instanceof'?

I don't understand what is the purpose of the Buffer.isBuffer function when instanceof works like a charm :
var b = new Buffer('blabla')
assert.ok(b instanceof Buffer)
Well, actually these are the same (currently at least):
-- lib/buffer.js:
Buffer.isBuffer = function isBuffer(b) {
return util.isBuffer(b);
};
-- lib/util.js:
function isBuffer(arg) {
return arg instanceof Buffer;
}
exports.isBuffer = isBuffer;
... so the only possible reason is readability. Note that before this specific implementation there was a set of macros for type checks, used when building the source. But it has been changed with this commit, and that was the reasoning:
Adding macros to Node's JS layer increases the barrier to
contributions, and it breaks programs that export Node's js files for
userland modules. (For example, several browserify transforms, my
readable-streams polyfill, the util-debuglog module, etc.) These are
not small problems.
I'd suggest checking the whole discussion in the commit's pull request.

RequireJS Dynamic Paths Replacement

I have a requirejs module which is used as a wrapper to an API that comes from a different JS file:
apiWrapper.js
define([], function () {
return {
funcA: apiFuncA,
funcB: apiFuncB
};
});
It works fine but now I have some new use cases where I need to replace the implementation, e.g. instead of apiFuncA invoke my own function. But I don't want to touch other places in my code, where I call the functions, like apiWrapper.funcA(param).
I can do something like the following:
define([], function () {
return {
funcA: function(){
if(regularUseCase){
return apiFuncA(arguments);
} else {
return (function myFuncAImplementation(params){
//my code, instead of the external API
})(arguments);
}
},
funcB: apiFuncB
};
});
But I feel like it doesn't look nice. What's a more elegant alternative? Is there a way to replace the module (apiWrapper) dynamically? Currently it's defined in my require.config paths definition. Can this path definition be changed at runtime so that I'll use a different file as a wrapper?
Well, first of all, if you use Require.js, you probably want to build it before production. As so, it is important you don't update paths dynamically at runtime or depends on runtime variables to defines path as this will prevent you from running r.js successfully.
There's a lot of tools (requirejs plugins) out there that can help you dynamically change the path to a module or conditionnaly load a dependency.
First, you could use require.replace that allow you to change parts (or all) of a module URL depending on a check you made without breaking the build.
If you're looking for polyfilling, there's requirejs feature
And there's a lot more listed here: https://github.com/jrburke/requirejs/wiki/Plugins

Dart2js : Is it possible to start Root Isolate from Javascript?

I have an application compiled in dart2js (Dart SDK version 0.6.13.0_r25630)
and I'd like to load it with RequireJS everytime I need.
First of all, thanks God for wrapper function in compiled javascript, but in my case is not enough :(
I use requirejs to load a dart2js application
require(["application.dart"], function () {});
but i would like to handle when to start the application. for example on click event.
require(["jQuery","application.dart"], function (jQuery,$) {
jQuery(element).click(function(){
$.startRootIsolate($.main$closure);
})
});
I hacked the compiled Javascript, but i'd like to know if it's possible in native way.
in application.dart.js I wrapped the function in a AMD module
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define([],function(){
return factory();
} );
} else {
// Browser globals.
factory();
}
})(function($) {...})
then I return $ Object
return $;
and finally i commented this line of code where i found
$.startRootIsolate($.main$closure);
Thanks everyone
marco
I doubt this is possible without hacking at the code as you have. However, Dart 1.6 added support for deferred loading which might give you an alternative way of doing what you need?
http://news.dartlang.org/2014/08/dart-16-adds-support-for-deferred.html

get information about current commonjs implementation

Is there a standard way of detecting the implementation (node.js, rhino etc) and ideally version of that implementation in CommonJS.
If not, what do people do to get it?
I'm thinking something akin to the HTTP User-Agent header in the browser world.
No, but you could detect whether you're inside node, for example:
if (typeof process !== 'undefined') {
console.log('node!');
}
If you wanted to be absolutely certain it's node:
if (typeof process !== 'undefined'
&& process && process.versions
&& process.versions.node) {
console.log('node version:', process.version);
}
I can't say for other environments, (I've never used Rhino).
But to answer your question more in-depth, Node doesn't have a strict "version" of CommonJS it implements. Node hasn't been catering to CommonJS specs for a long time now (aside from the recent AMD implementation, which wasn't a full implementation anyway).

Resources