Jump to Table of Contents

Example: Programatically use Loader

Loader can be used programatically as an offline dependency calculator.

Instantiating Loader

Loader comes with the YUI seed file by default, so it's ready to be used immediately, so there is no need to load any additional files.

var Y = YUI();
var loader = new Y.Loader();

Resolving dependencies

Loader comes with a resolve method that it uses internally to calculate dependencies and build URL's for injecting scripts into the page.

var Y = YUI();
var loader = new Y.Loader({
    require: [ 'node' ]
});

//Tell loader to calculate dependencies
loader.calculate();

var out = loader.resolve();

In the above code, out will be an Object containing the keys, js and css that will contain an array of URL's to load the modules needed to resolve node.

Advanced Usage

var Y = YUI();
var loader = new Y.Loader({
    combine: true,
    comboBase: 'http://mysite.com/yui-combo?',
    root: '',
    base: '',
    ignoreRegistered: true,
    require: [ 'node' ]
});

var out = loader.resolve(true);

The above code will generate this URL for you:

You can use any Loader configuration option here as well: modules, groups, patterns, etc.

CLI use within Node.js

Here we use Loader to calculate dependencies from the command line and generate a combined file. This could be used in a build system to auto-generate a custom seed file with modules needed for immediate access.

#!/usr/bin/env node

var path = require('path'),
    fs = require('fs'),
    YUI = require('yui').YUI,
    Y = YUI();

//Create the loader instance
var loader = new Y.Loader({
    //Setup the base path that your YUI files live in
    base: path.join(__dirname, './node_modules/yui/'),
    //Ignore all registered modules
    ignoreRegistered: true,
    //require node
    require: ['node']
});

//Resolve these file (passing true calculates the dependencies for you)
var out = loader.resolve(true);


var str = [];

//Now walk the list of resolved files
out.js.forEach(function(file) {
    //Read the files
    str.push(fs.readFileSync(file, 'utf8'));
});

//Write all the files out into a single file
fs.writeFileSync('./combined.js', str.join('\n'), 'utf8');