webpack/lib/JsonGenerator.js

57 lines
1.4 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 23:08:51 +08:00
"use strict";
const { ConcatSource, RawSource } = require("webpack-sources");
2018-04-25 06:35:58 +08:00
const stringifySafe = data => {
const stringified = JSON.stringify(data);
if (!stringified) {
return undefined; // Invalid JSON
}
return stringified.replace(
2018-02-25 09:00:20 +08:00
/\u2028|\u2029/g,
str => (str === "\u2029" ? "\\u2029" : "\\u2028")
); // invalid in JavaScript but valid JSON
2018-04-25 06:35:58 +08:00
};
class JsonGenerator {
generate(module, dependencyTemplates, runtimeTemplate) {
const source = new ConcatSource();
const data = module.buildInfo.jsonData;
if (data === undefined) {
return new RawSource(
runtimeTemplate.missingModuleStatement({
request: module.rawRequest
})
);
}
2018-02-25 09:00:20 +08:00
if (
Array.isArray(module.buildMeta.providedExports) &&
!module.isUsed("default")
) {
// Only some exports are used: We can optimize here, by only generating a part of the JSON
const reducedJson = {};
2018-02-25 09:00:20 +08:00
for (const exportName of module.buildMeta.providedExports) {
if (exportName === "default") continue;
const used = module.isUsed(exportName);
2018-02-25 09:00:20 +08:00
if (used) {
reducedJson[used] = data[exportName];
}
}
2018-02-25 09:00:20 +08:00
source.add(
`${module.moduleArgument}.exports = ${stringifySafe(reducedJson)};`
);
} else {
source.add(`${module.moduleArgument}.exports = ${stringifySafe(data)};`);
}
return source;
}
}
module.exports = JsonGenerator;