grafana/scripts/webpack/plugins/HTMLWebpackCSSChunks.js
Jack Westbrook 78bef7a26a
Build: Enable long term caching for frontend assets (#47625)
* build(webpack): move CopyUniconsPlugin into own file

* chore(webpack): delete unused blobUrl and compile loaders

* build(webpack): prefer contenthash over fullhash for longer caching

* build(webpack): set optimization.moduleIds named only in dev

* build(webpack): introduce HTMLWebpackCSSChunks so templates can access theme css by name

* feat: inject css files with contenthash in html templates

* revert(error-template): remove ContentDeliveryURL from CSS href

* refactor(index-template): update grafanaBootData.themePaths

* chore(webpack): add typescript annotations for CopyUniconsPlugin
2022-05-26 11:49:18 +02:00

43 lines
1.3 KiB
JavaScript

const HtmlWebpackPlugin = require('html-webpack-plugin');
/*
* This plugin returns the css associated with entrypoints. Those chunks can be found
* in `htmlWebpackPlugin.files.cssChunks`.
* The HTML Webpack plugin removed the chunks object in v5 in favour of an array however if we want
* to do anything smart with hashing (e.g. [contenthash]) we need a map of { themeName: chunkNameWithHash }.
*/
class HTMLWebpackCSSChunks {
/**
* @param {import('webpack').Compiler} compiler
*/
apply(compiler) {
compiler.hooks.compilation.tap(
'HTMLWebpackCSSChunks',
/**
* @param {import('webpack').Compilation} compilation
*/
(compilation) => {
HtmlWebpackPlugin.getHooks(compilation).beforeAssetTagGeneration.tapAsync(
'HTMLWebpackCSSChunks',
(data, cb) => {
data.assets.cssChunks = {};
for (const entryPoint of compilation.entrypoints.values()) {
for (const chunk of entryPoint.chunks) {
const cssFile = [...chunk.files].find((file) => file.endsWith('.css'));
if (cssFile !== undefined) {
data.assets.cssChunks[chunk.name] = cssFile;
}
}
}
cb(null, data);
}
);
}
);
}
}
module.exports = HTMLWebpackCSSChunks;