-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
92 lines (72 loc) · 2.4 KB
/
index.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
88
89
90
91
92
"use strict";
var path = require('path');
var fs = require('fs');
var getCallsiteDirname = require('get-callsite-dirname');
var resolve = require('resolve/lib/sync');
var isString = require('lodash').isString;
var handleCSS = require('./handlers/css');
function createRegistry(options) {
options = options || {};
var root = options.root || process.cwd();
var prefix = options.prefix || process.env.REQUIRE_ASSETS_PREFIX || '';
var handlers = options.handlers || {};
if (!handlers.css)
handlers.css = handleCSS;
var registry = {
mapping: {},
handlers: handlers,
root: root,
prefix: prefix,
toJSON: function() {
return registry.mapping;
},
createURL: function(filename) {
return path.join(registry.prefix, path.relative(registry.root, filename));
},
addMapping: function(filename, url) {
url = url || registry.createURL(filename);
var extname = path.extname(filename);
var handler = registry.handlers[extname.slice(1)];
return registry.mapping[url] = handler ?
handler(filename, url, registry) :
{filename: filename, result: url};
},
requireAssets: function(id, basedir) {
basedir = basedir || getCallsiteDirname();
var filename = resolve(id, {basedir: basedir});
return registry.addMapping(filename).result;
}
};
return registry;
}
function fromJSON(data, options) {
if (isString(data))
data = JSON.parse(data);
var registry = createRegistry(options);
registry.mapping = data;
return registry;
}
function fromFile(filename, options) {
var data = fs.readFileSync(filename, 'utf8');
return fromJSON(data);
}
function requireAssets(id, basedir) {
basedir = basedir || getCallsiteDirname();
return process.__requireAssetsRegistry.requireAssets(id, basedir);
}
function configureRegistry(registry) {
process.__requireAssetsRegistry = registry;
}
function currentRegistry() {
return process.__requireAssetsRegistry;
}
if (!process.__requireAssetsRegistry) {
process.__requireAssetsRegistry = createRegistry();
}
module.exports = requireAssets;
module.exports.requireAssets = requireAssets;
module.exports.currentRegistry = currentRegistry;
module.exports.configureRegistry = configureRegistry
module.exports.createRegistry = createRegistry;
module.exports.fromJSON = fromJSON;
module.exports.fromFile = fromFile;