inline encode function

This commit is contained in:
Tobias Koppers 2019-11-26 09:53:47 +01:00
parent 5f8ad0dd67
commit cf3f7be8d1
1 changed files with 29 additions and 35 deletions

View File

@ -82,40 +82,6 @@ const prepareOptions = (options = {}) => {
};
};
/**
* @param {NormalModule} module a module to encode
* @param {AssetModulesPluginOptions} options the options to the encoder
* @returns {string|null} encoded source
*/
const encode = (module, options) => {
if (shouldEmitAsset(module, options)) {
return null;
}
const originalSource = module.originalSource();
let content = originalSource.source();
if (typeof options.dataUrl === "function") {
return options.dataUrl.call(null, content, module.nameForCondition());
}
// @ts-ignore non-false dataUrl ensures in shouldEmitAsset above
const encoding = options.dataUrl.encoding;
const extname = path.extname(module.nameForCondition());
// @ts-ignore non-false dataUrl ensures in shouldEmitAsset above
const mimeType = options.dataUrl.mimetype || mime.getType(extname);
if (encoding === "base64") {
if (typeof content === "string") {
content = Buffer.from(content);
}
content = content.toString("base64");
}
return `data:${mimeType}${encoding ? `;${encoding}` : ""},${content}`;
};
const JS_TYPES = new Set(["javascript"]);
const JS_AND_ASSET_TYPES = new Set(["javascript", "asset"]);
@ -143,7 +109,35 @@ class AssetGenerator extends Generator {
runtimeRequirements.add(RuntimeGlobals.module);
if (!shouldEmitAsset(module, this.options)) {
const encodedSource = encode(module, this.options);
const originalSource = module.originalSource();
let content = originalSource.source();
let encodedSource;
if (typeof this.options.dataUrl === "function") {
encodedSource = this.options.dataUrl.call(
null,
content,
module.nameForCondition()
);
} else {
// @ts-ignore non-false dataUrl ensures in shouldEmitAsset above
const encoding = this.options.dataUrl.encoding;
const extname = path.extname(module.nameForCondition());
// @ts-ignore non-false dataUrl ensures in shouldEmitAsset above
const mimeType = this.options.dataUrl.mimetype || mime.getType(extname);
if (encoding === "base64") {
if (typeof content === "string") {
content = Buffer.from(content);
}
content = content.toString("base64");
}
encodedSource = `data:${mimeType}${
encoding ? `;${encoding}` : ""
},${content}`;
}
return new RawSource(
`${RuntimeGlobals.module}.exports = ${JSON.stringify(encodedSource)};`
);