requirejs2读书笔记

时间:2023-03-08 17:10:34
requirejs2读书笔记

If you want to do require() calls in the HTML page, then it is best to not use data-main. data-main is only intended for use when the page just has one main entry point, the data-main script. For pages that want to do inline require() calls, it is best to nest those inside a require() call for the configuration:

<script src="scripts/require.js"></script>

<script>

require(['scripts/config'], function() {

    // Configuration loaded now, safe to do other require calls

    // that depend on that config.

    require(['foo'], function(foo) {

    });

});

</script>

If the module does not have any dependencies, and it is just a collection of name/value pairs, then just pass an object literal to define():

If the module does not have any dependencies, and it is just a collection of name/value pairs, then just pass an object literal to define():
//Inside file my/shirt.js: 如果没有定义模块名称,那所在的文件路径就是模块名
define({
color: "black",
size: "unisize"
});

If you wish to reuse some code that was written in the traditional CommonJS module format it may be difficult to re-work to the array of dependencies used above, and you may prefer to have direct alignment of dependency name to the local variable used for that dependency. You can use the simplified CommonJS wrapper for those cases:

define(function(require, exports, module) {
var a = require('a'),
b = require('b'); //Return the module value
return function () {};
}
);

This wrapper relies on Function.prototype.toString() to give a useful string value of the function contents. This does not work on some devices like the PS3 and some older Opera mobile browsers. Use the optimizer to pull out the dependencies in the array format for use on those devices.

More information is available on the CommonJS page, and in the "Sugar" section in the Why AMD page.

Console debugging: If you need to work with a module you already loaded via a require(["module/name"], function(){}) call in the JavaScript console, then you can use the require() form that just uses the string name of the module to fetch it:

require("module/name").callSomeFunction()

Note this only works if "module/name" was previously loaded via the async version of require: require(["module/name"]). If using a relative path, like './module/name', those only work inside define

Errbacks, when used with requirejs.undef(), will allow you to detect if a module fails to load, undefine that module, reset the config to a another location, then try again.

A common use case for this is to use a CDN-hosted version of a library, but if that fails, switch to loading the file locally:

requirejs.config({
enforceDefine: true,
paths: {
jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min'
}
}); //Later
require(['jquery'], function ($) {
//Do something with $ here
}, function (err) {
//The errback, error callback
//The error has a list of modules that failed
var failedId = err.requireModules && err.requireModules[0];
if (failedId === 'jquery') {
//undef is function only on the global requirejs object.
//Use it to clear internal knowledge of jQuery. Any modules
//that were dependent on jQuery and in the middle of loading
//will not be loaded yet, they will wait until a valid jQuery
//does load.
requirejs.undef(failedId); //Set the path to jQuery to local path
requirejs.config({
paths: {
jquery: 'local/jquery'
}
}); //Try again. Note that the above require callback
//with the "Do something with $ here" comment will
//be called if this new attempt to load jQuery succeeds.
require(['jquery'], function () {});
} else {
//Some other error. Maybe show message to the user.
}
});

With `requirejs.undef()`, if you later set up a different config and try to load the same module, the loader will still remember which modules needed that dependency and finish loading them when the newly configured module loads.

Note: errbacks only work with callback-style require calls, not define() calls. define() is only for declaring modules.

The optimizer is part of the r.js adapter for Node and Nashorn, and it is designed to be run as part of a build or packaging step after you are done with development and are ready to deploy the code for your users.

The optimizer will only combine modules that are specified in arrays of string literals that are passed to top-level require and define calls, or the require('name') string literal calls in a simplified CommonJS wrapping. So, it will not find modules that are loaded via a variable name:

var mods = someCondition ? ['a', 'b'] : ['c', 'd'];

require(mods);

but 'a' and 'b' will be included if specified like so:

require(['a', 'b']);

or:

define(['a', 'b'], function (a, b) {});

Note the build limitations of shim config. In particular, you cannot load dependencies for shimmed libraries from a CDN. See the shim config section for more information.