|
| 1 | +/* eslint-env browser */ |
| 2 | +import path from "path"; |
| 3 | + |
| 4 | +import { Template } from "webpack"; |
| 5 | + |
| 6 | +import MiniCssExtractPlugin from "../src"; |
| 7 | + |
| 8 | +import { runInJsDom, compile, getCompiler } from "./helpers/index"; |
| 9 | + |
| 10 | +describe("hooks", () => { |
| 11 | + it(`beforeTagInsert`, async () => { |
| 12 | + const webpackCompiler = getCompiler( |
| 13 | + "insert.js", |
| 14 | + {}, |
| 15 | + { |
| 16 | + mode: "none", |
| 17 | + output: { |
| 18 | + publicPath: "", |
| 19 | + path: path.resolve(__dirname, "../outputs"), |
| 20 | + filename: "[name].bundle.js", |
| 21 | + }, |
| 22 | + plugins: [ |
| 23 | + new MiniCssExtractPlugin({ |
| 24 | + filename: "[name].css", |
| 25 | + }), |
| 26 | + { |
| 27 | + /** |
| 28 | + * |
| 29 | + * @param {import('webpack').Compiler} compiler |
| 30 | + */ |
| 31 | + apply: (compiler) => { |
| 32 | + compiler.hooks.compilation.tap("sri", (compilation) => { |
| 33 | + MiniCssExtractPlugin.getCompilationHooks( |
| 34 | + compilation |
| 35 | + ).beforeTagInsert.tap("sri", (source, varNames) => |
| 36 | + Template.asString([ |
| 37 | + source, |
| 38 | + `${varNames.tag}.setAttribute("integrity", "sriHashes[${varNames.chunkId}]");`, |
| 39 | + ]) |
| 40 | + ); |
| 41 | + }); |
| 42 | + }, |
| 43 | + }, |
| 44 | + { |
| 45 | + /** |
| 46 | + * |
| 47 | + * @param {import('webpack').Compiler} compiler |
| 48 | + */ |
| 49 | + apply: (compiler) => { |
| 50 | + compiler.hooks.compilation.tap("href", (compilation) => { |
| 51 | + MiniCssExtractPlugin.getCompilationHooks( |
| 52 | + compilation |
| 53 | + ).beforeTagInsert.tap("changeHref", (source, varNames) => |
| 54 | + Template.asString([ |
| 55 | + source, |
| 56 | + `${varNames.tag}.setAttribute("href", "https://github.com/webpack-contrib/mini-css-extract-plugin");`, |
| 57 | + ]) |
| 58 | + ); |
| 59 | + }); |
| 60 | + }, |
| 61 | + }, |
| 62 | + ], |
| 63 | + } |
| 64 | + ); |
| 65 | + const stats = await compile(webpackCompiler); |
| 66 | + runInJsDom("main.bundle.js", webpackCompiler, stats, (dom) => { |
| 67 | + const [tag] = dom.window.document.head.getElementsByTagName("link"); |
| 68 | + expect(tag.getAttribute("integrity")).toBe("sriHashes[chunkId]"); |
| 69 | + expect(tag.getAttribute("href")).toBe( |
| 70 | + "https://github.com/webpack-contrib/mini-css-extract-plugin" |
| 71 | + ); |
| 72 | + }); |
| 73 | + }); |
| 74 | +}); |
0 commit comments