|
| 1 | +/** |
| 2 | + * Copyright 2018 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not |
| 5 | + * use this file except in compliance with the License. You may obtain a copy of |
| 6 | + * the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | + * License for the specific language governing permissions and limitations under |
| 14 | + * the License. |
| 15 | + * |
| 16 | + * https://github.com/GoogleChromeLabs/critters/blob/main/packages/critters-webpack-plugin/src/index.js |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * Critters does not (yet) support `html-webpack-plugin` v5, so we vendor it. |
| 21 | + */ |
| 22 | + |
| 23 | +const path = require('path'); |
| 24 | +const minimatch = require('minimatch'); |
| 25 | +const { sources } = require('webpack'); |
| 26 | +const Critters = require('critters'); |
| 27 | +const HtmlWebpackPlugin = require('html-webpack-plugin'); |
| 28 | + |
| 29 | +function tap(inst, hook, pluginName, async, callback) { |
| 30 | + if (inst.hooks) { |
| 31 | + const camel = hook.replace(/-([a-z])/g, (_s, i) => i.toUpperCase()); |
| 32 | + inst.hooks[camel][async ? 'tapAsync' : 'tap'](pluginName, callback); |
| 33 | + } else { |
| 34 | + inst.plugin(hook, callback); |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +// Used to annotate this plugin's hooks in Tappable invocations |
| 39 | +const PLUGIN_NAME = 'critters-webpack-plugin'; |
| 40 | + |
| 41 | +/** |
| 42 | + * Create a Critters plugin instance with the given options. |
| 43 | + * @public |
| 44 | + * @param {import('critters').Options} options Options to control how Critters inlines CSS. See https://github.com/GoogleChromeLabs/critters#usage |
| 45 | + * @example |
| 46 | + * // webpack.config.js |
| 47 | + * module.exports = { |
| 48 | + * plugins: [ |
| 49 | + * new Critters({ |
| 50 | + * // Outputs: <link rel="preload" onload="this.rel='stylesheet'"> |
| 51 | + * preload: 'swap', |
| 52 | + * |
| 53 | + * // Don't inline critical font-face rules, but preload the font URLs: |
| 54 | + * preloadFonts: true |
| 55 | + * }) |
| 56 | + * ] |
| 57 | + * } |
| 58 | + */ |
| 59 | +module.exports = class CrittersWebpackPlugin extends Critters { |
| 60 | + /** |
| 61 | + * @param {import('critters').Options} options |
| 62 | + */ |
| 63 | + constructor(options) { |
| 64 | + super(options); |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Invoked by Webpack during plugin initialization |
| 69 | + */ |
| 70 | + apply(compiler) { |
| 71 | + // hook into the compiler to get a Compilation instance... |
| 72 | + tap(compiler, 'compilation', PLUGIN_NAME, false, compilation => { |
| 73 | + this.options.path = compiler.options.output.path; |
| 74 | + this.options.publicPath = compiler.options.output.publicPath; |
| 75 | + |
| 76 | + const handleHtmlPluginData = (htmlPluginData, callback) => { |
| 77 | + this.fs = compilation.outputFileSystem; |
| 78 | + this.compilation = compilation; |
| 79 | + this.process(htmlPluginData.html) |
| 80 | + .then(html => { |
| 81 | + callback(null, { html }); |
| 82 | + }) |
| 83 | + .catch(callback); |
| 84 | + }; |
| 85 | + |
| 86 | + HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync( |
| 87 | + PLUGIN_NAME, |
| 88 | + handleHtmlPluginData |
| 89 | + ); |
| 90 | + }); |
| 91 | + } |
| 92 | + |
| 93 | + /** |
| 94 | + * Given href, find the corresponding CSS asset |
| 95 | + */ |
| 96 | + async getCssAsset(href, style) { |
| 97 | + const outputPath = this.options.path; |
| 98 | + const publicPath = this.options.publicPath; |
| 99 | + |
| 100 | + // CHECK - the output path |
| 101 | + // path on disk (with output.publicPath removed) |
| 102 | + let normalizedPath = href.replace(/^\//, ''); |
| 103 | + const pathPrefix = (publicPath || '').replace(/(^\/|\/$)/g, '') + '/'; |
| 104 | + if (normalizedPath.indexOf(pathPrefix) === 0) { |
| 105 | + normalizedPath = normalizedPath |
| 106 | + .substring(pathPrefix.length) |
| 107 | + .replace(/^\//, ''); |
| 108 | + } |
| 109 | + const filename = path.resolve(outputPath, normalizedPath); |
| 110 | + |
| 111 | + // try to find a matching asset by filename in webpack's output (not yet written to disk) |
| 112 | + const relativePath = path |
| 113 | + .relative(outputPath, filename) |
| 114 | + .replace(/^\.\//, ''); |
| 115 | + const asset = this.compilation.assets[relativePath]; // compilation.assets[relativePath]; |
| 116 | + |
| 117 | + // Attempt to read from assets, falling back to a disk read |
| 118 | + let sheet = asset && asset.source(); |
| 119 | + |
| 120 | + if (!sheet) { |
| 121 | + try { |
| 122 | + sheet = await this.readFile(this.compilation, filename); |
| 123 | + this.logger.warn( |
| 124 | + `Stylesheet "${relativePath}" not found in assets, but a file was located on disk.${ |
| 125 | + this.options.pruneSource |
| 126 | + ? ' This means pruneSource will not be applied.' |
| 127 | + : '' |
| 128 | + }` |
| 129 | + ); |
| 130 | + } catch (e) { |
| 131 | + this.logger.warn(`Unable to locate stylesheet: ${relativePath}`); |
| 132 | + return; |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + style.$$asset = asset; |
| 137 | + style.$$assetName = relativePath; |
| 138 | + // style.$$assets = this.compilation.assets; |
| 139 | + |
| 140 | + return sheet; |
| 141 | + } |
| 142 | + |
| 143 | + checkInlineThreshold(link, style, sheet) { |
| 144 | + const inlined = super.checkInlineThreshold(link, style, sheet); |
| 145 | + |
| 146 | + if (inlined) { |
| 147 | + const asset = style.$$asset; |
| 148 | + if (asset) { |
| 149 | + delete this.compilation.assets[style.$$assetName]; |
| 150 | + } else { |
| 151 | + this.logger.warn( |
| 152 | + ` > ${style.$$name} was not found in assets. the resource may still be emitted but will be unreferenced.` |
| 153 | + ); |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + return inlined; |
| 158 | + } |
| 159 | + |
| 160 | + /** |
| 161 | + * Inline the stylesheets from options.additionalStylesheets (assuming it passes `options.filter`) |
| 162 | + */ |
| 163 | + async embedAdditionalStylesheet(document) { |
| 164 | + const styleSheetsIncluded = []; |
| 165 | + (this.options.additionalStylesheets || []).forEach(cssFile => { |
| 166 | + if (styleSheetsIncluded.includes(cssFile)) { |
| 167 | + return; |
| 168 | + } |
| 169 | + styleSheetsIncluded.push(cssFile); |
| 170 | + const webpackCssAssets = Object.keys(this.compilation.assets).filter( |
| 171 | + file => minimatch(file, cssFile) |
| 172 | + ); |
| 173 | + webpackCssAssets.map(asset => { |
| 174 | + const style = document.createElement('style'); |
| 175 | + style.$$external = true; |
| 176 | + style.textContent = this.compilation.assets[asset].source(); |
| 177 | + document.head.appendChild(style); |
| 178 | + }); |
| 179 | + }); |
| 180 | + } |
| 181 | + |
| 182 | + /** |
| 183 | + * Prune the source CSS files |
| 184 | + */ |
| 185 | + pruneSource(style, before, sheetInverse) { |
| 186 | + const isStyleInlined = super.pruneSource(style, before, sheetInverse); |
| 187 | + const asset = style.$$asset; |
| 188 | + const name = style.$$name; |
| 189 | + |
| 190 | + if (asset) { |
| 191 | + // if external stylesheet would be below minimum size, just inline everything |
| 192 | + const minSize = this.options.minimumExternalSize; |
| 193 | + if (minSize && sheetInverse.length < minSize) { |
| 194 | + // delete the webpack asset: |
| 195 | + delete this.compilation.assets[style.$$assetName]; |
| 196 | + return true; |
| 197 | + } |
| 198 | + this.compilation.assets[style.$$assetName] = |
| 199 | + new sources.LineToLineMappedSource( |
| 200 | + sheetInverse, |
| 201 | + style.$$assetName, |
| 202 | + before |
| 203 | + ); |
| 204 | + } else { |
| 205 | + this.logger.warn( |
| 206 | + 'pruneSource is enabled, but a style (' + |
| 207 | + name + |
| 208 | + ') has no corresponding Webpack asset.' |
| 209 | + ); |
| 210 | + } |
| 211 | + |
| 212 | + return isStyleInlined; |
| 213 | + } |
| 214 | +}; |
0 commit comments