42 lines
1.2 KiB
JavaScript
42 lines
1.2 KiB
JavaScript
const path = require("path");
|
|
const mime = require("mime");
|
|
const fs = require("fs");
|
|
|
|
class Base64ImagePlugin {
|
|
constructor(options = {}) {
|
|
this.test = options.test || /\.(png|jpe?g|gif|svg)$/;
|
|
}
|
|
|
|
apply(compiler) {
|
|
compiler.hooks.normalModuleFactory.tap("Base64ImagePlugin", (factory) => {
|
|
factory.hooks.beforeResolve.tapAsync(
|
|
"Base64ImagePlugin",
|
|
(data, callback) => {
|
|
if (!data) return callback();
|
|
if (this.test.test(data.request)) {
|
|
const filePath = path.resolve(data.context, data.request);
|
|
fs.readFile(filePath, (err, content) => {
|
|
if (err) return callback();
|
|
const mimeType = mime.getType(filePath);
|
|
const base64 = `module.exports = "data:${mimeType};base64,${content.toString(
|
|
"base64"
|
|
)}"`;
|
|
data.loaders = [
|
|
{
|
|
loader: path.resolve(__dirname, "inline-base64-loader.js"),
|
|
options: { base64 },
|
|
},
|
|
];
|
|
callback(null, data);
|
|
});
|
|
} else {
|
|
callback(null, data);
|
|
}
|
|
}
|
|
);
|
|
});
|
|
}
|
|
}
|
|
|
|
module.exports = Base64ImagePlugin;
|