forked from SBoudrias/require.replace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
require.replace.js
87 lines (66 loc) · 1.92 KB
/
require.replace.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*!
* require.replace.js
* https://github.com/SBoudrias/require.replace
*
* Copyright (c) 2013, Simon Boudrias
* Licensed under the MIT license.
*/
(function () {
"use strict";
var toString = Object.prototype.toString;
var aIndexOf = Array.prototype.indexOf || function( needle ) {
for(var i = 0; i < this.length; i++) {
if( this[i] === needle ) {
return i;
}
}
return -1;
};
define({
version: "0.3.0",
// ---
// Called when a dependency needs to be loaded.
load: function (name, req, onLoad, config) {
var needle = '', partials;
if( name.indexOf(':') > -1 ) {
partials = name.split(':');
name = partials[0];
needle = partials[1];
}
if( !config.config.replace ) {
throw new Error("Require.replace need to be configured");
}
var replaceConfig = config.config.replace,
moduleConfig = replaceConfig[name] || replaceConfig,
toLoad = [],
shouldRun = config.isBuild ? moduleConfig.optimize : true,
pattern, value, path;
(function() {
// Skip if we"re in build process and config.optimize is set to false
if ( !shouldRun ) return;
pattern = moduleConfig.pattern;
value = moduleConfig.value;
if( toString.call(moduleConfig.value) === "[object Function]" ) {
value = moduleConfig.value(needle);
}
// skip if the `value` is contained in the ignored value list
if( moduleConfig.ignore
&& aIndexOf.call( moduleConfig.ignore, value ) >= 0 ) return;
// If there's a `paths` config, use it
if ( config.paths[name] ) {
// @note: This override the defined path config to work with shimmed
// modules.
config.paths[name] = config.paths[name].replace( pattern, value );
toLoad.push( name );
// else, the name is a path
} else {
path = name.replace( pattern, value );
toLoad.push( path );
}
}());
req(toLoad, function ( value ) {
onLoad( value );
});
}
});
}());