This repository has been archived by the owner on Oct 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
json.js
51 lines (43 loc) · 1.5 KB
/
json.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
/*
JSON plugin
*/
// this code allows named exports of valid identifiers in json to work with rollup
// so you can effectively "pick" a json value and have the other base-level json values excluded
// not comprehensive of course
function isValidIdentifier(exportName) {
return exportName.match(/^[a-zA-Z_$][0-9a-zA-Z_$]*$/);
}
module.exports = {
translate: function(load) {
var json = JSON.parse(load.source);
if (this.builder && this.transpiler && !Array.isArray(json)) {
load.metadata.format = 'esm';
var namedExports = Object.keys(json);
var validIdentifiers = namedExports.filter(isValidIdentifier);
var output = ['exp' + 'ort var __useDefault = true;\n'];
validIdentifiers.forEach(function (exportName) {
output.push('exp' + 'ort var ' + exportName + ' = ' + JSON.stringify(json[exportName]) + ';\n');
});
output.push('exp' + 'ort default {\n');
namedExports.forEach(function (exportName) {
if (validIdentifiers.indexOf(exportName) !== -1) {
output.push(exportName + ': ' + exportName + ',\n');
}
else {
output.push(JSON.stringify(exportName) + ': ' + JSON.stringify(json[exportName]) + ',\n');
}
});
output.push('};');
return output.join('');
}
if (this.builder) {
load.metadata.format = 'cjs';
return 'module.exports = ' + JSON.stringify(json);
}
},
instantiate: function(load) {
if (!this.builder) {
return JSON.parse(load.source);
}
}
}