56 lines
1.6 KiB
JavaScript
56 lines
1.6 KiB
JavaScript
const path = require("path");
|
|
|
|
class DynamicPublicPathPlugin {
|
|
apply(compiler) {
|
|
compiler.hooks.emit.tapAsync(
|
|
"DynamicPublicPathPlugin",
|
|
(compilation, callback) => {
|
|
const assets = Object.keys(compilation.assets).filter(
|
|
(file) => file.endsWith(".js") || file.endsWith(".css")
|
|
);
|
|
|
|
const scriptTags = assets
|
|
.map((file) => {
|
|
// const ext = path.extname(file);
|
|
// if (ext === ".js") {
|
|
// return `<script src="\${window.__BASE_PATH__}${file}"></script>`;
|
|
// } else if (ext === ".css") {
|
|
// return `<link href="\${window.__BASE_PATH__}${file}" rel="stylesheet">`;
|
|
// }
|
|
// return "";
|
|
return `'${file}'`;
|
|
})
|
|
.join(",");
|
|
|
|
console.log(scriptTags);
|
|
|
|
const htmlAsset = compilation.assets["index.html"];
|
|
if (htmlAsset) {
|
|
const htmlContent = htmlAsset.source().toString();
|
|
const replacedHtml = htmlContent.replace(
|
|
"[]//inject",
|
|
`[${scriptTags}]//inject`
|
|
);
|
|
|
|
const timestamp = new Date().getTime();
|
|
const finalHtml = replacedHtml.replace(
|
|
"</body>",
|
|
`<script>window.__TIMESTAMP__ = ${timestamp};</script></body>`
|
|
);
|
|
|
|
console.log(finalHtml);
|
|
|
|
compilation.assets["index.html"] = {
|
|
source: () => finalHtml,
|
|
size: () => finalHtml.length,
|
|
};
|
|
}
|
|
|
|
callback();
|
|
}
|
|
);
|
|
}
|
|
}
|
|
|
|
module.exports = DynamicPublicPathPlugin;
|