Skip to content

Instantly share code, notes, and snippets.

@xiaopc
Created June 30, 2021 14:04
Show Gist options
  • Save xiaopc/b92ac3384e51bfad984945d80c364bb6 to your computer and use it in GitHub Desktop.
Save xiaopc/b92ac3384e51bfad984945d80c364bb6 to your computer and use it in GitHub Desktop.
const assert = require('assert');
const assign = require('object-assign');
const htmlWebpackPlugin = require('html-webpack-plugin');
const htmlTags = require('html-webpack-plugin/lib/html-tags');
const createHtmlTag = htmlTags.createHtmlTagObject, htmlTagToString = htmlTags.htmlTagObjectToString;
const isStylesheetLink = (def) => def.tagName === 'link' && def.attributes.rel === 'stylesheet' && def.attributes.href;
const addMediaAttribute = (tag) => {
tag.attributes.media = 'print';
tag.attributes.onload = "this.media='all'; this.onload=null";
};
const getNoscript = (tag) => {
let linkTag = createHtmlTag('link', {rel: 'stylesheet', href: tag.attributes.href});
let inner = htmlTagToString(linkTag);
return createHtmlTag('noscript', {}, inner);
}
class CSSLoaderHTMLWebpackPlugin {
constructor(options) {
assert.strictEqual(options, undefined, `${this.constructor.name} does not accept any options`);
}
apply(compiler) {
compiler.hooks.compilation.tap(this.constructor.name, (compilation) => {
htmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync(this.constructor.name, (data, cb) => {
let additionalTags = [];
data.headTags.map((tag) => {
if (isStylesheetLink(tag)) {
addMediaAttribute(tag);
additionalTags.push(getNoscript(tag));
}
});
data.headTags = data.headTags.concat(additionalTags);
cb(null, data);
});
});
}
}
module.exports = CSSLoaderHTMLWebpackPlugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment