Skip to content

Instantly share code, notes, and snippets.

@jrburke
Last active February 11, 2024 23:19
Show Gist options
  • Save jrburke/6472536 to your computer and use it in GitHub Desktop.
Save jrburke/6472536 to your computer and use it in GitHub Desktop.
Building a file with external dependencies that could be from AMD, node, or globals.
//run in node to do the build
var requirejs = require('requirejs'),
fs = require('fs'),
depsRegExp = /\/\*DEPENDENCIES\*\//,
globalMapRegExp = /\/\*GLOBALMAP\*\//,
shimmer = fs.readFileSync('shimmer.js', 'utf8'),
wrapStart = fs.readFileSync('wrap.start', 'utf8');
// You could generate these with code if you want a dynamic build script
var dependencies = ['a', 'b', 'c'],
globalMap = {
'a': 'A',
'b': 'B',
'c': 'C'
};
// Modify wrapStart and shimmer to have the dependencies
var stringifiedDeps = JSON.stringify(dependencies);
shimmer = shimmer.replace(depsRegExp, stringifiedDeps);
wrapStart = wrapStart
.replace(depsRegExp, stringifiedDeps)
.replace(globalMapRegExp, JSON.stringify(globalMap));
// Do the optimization
requirejs.optimize({
rawText: {
'shimmer': shimmerText
},
include: ['almond', 'shimmer', 'what', 'ever'],
wrap: {
start: wrapStart,
end: fs.readFileSync('wrap.end', 'utf8')
},
out: 'built.js'
});
// this is the build output
//START wrap.start file
(function (root, factory, define) {
if (!define) {
// For the dark ages
var globals = {
'a': 'A',
'b': 'B',
'c': 'C'
};
define = function(deps, fn) {
fn(deps.map(function(dep) {
if (typeof require === 'function') {
// node
return require(dep);
} else {
// the dark ages
return root[globals[dep]];
}
}));
};
}
define(['a', 'b', 'c'], factory);
}(this, function () {
var outsideDeps = [].call(arguments, 0);
//END wrap.start file
// almond or some basic AMD provider is included here
// START shimmer.js
function makeFactory(i) {
return function() { return outsideDeps[i]; };
}
['a', 'b', 'c'].forEach(function(depId, i) {
define(depId, makeFactory(i));
});
// END shimmer.js
// other inlined modules here, 'what' and 'ever' in example
// START wrap.end file
}, typeof define === 'function' && define.amd ? define : undefined);
// END wrap.end file
function makeFactory(i) {
return function() { return outsideDeps[i]; };
}
/*DEPENDENCIES*/.forEach(function(depId, i) {
define(depId, makeFactory(i));
});
}, typeof define === 'function' && define.amd ? define : undefined);
(function (root, factory, define) {
if (!define) {
// For the dark ages
var globals = /*GLOBALMAP*/;
define = function(deps, fn) {
fn(deps.map(function(dep) {
if (typeof require === 'function') {
// node
return require(dep);
} else {
// the dark ages
return root[globals[dep]];
}
}));
};
}
define(/*DEPENDENCIES*/, factory);
}(this, function () {
var outsideDeps = [].call(arguments, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment