From f9c94f0027872cbdf58cbfb00f33357736cbe4b3 Mon Sep 17 00:00:00 2001 From: Jordan Pittman Date: Wed, 3 Mar 2021 09:05:49 -0500 Subject: [PATCH] feat: support registering webpack build dependencies --- src/index.js | 4 +++ test/__snapshots__/loader.test.js.snap | 4 +++ test/loader.test.js | 49 ++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) diff --git a/src/index.js b/src/index.js index 9d359720..c6d37e72 100644 --- a/src/index.js +++ b/src/index.js @@ -124,6 +124,10 @@ export default async function loader(content, sourceMap, meta) { this.addDependency(message.file); } + if (message.type === "build-dependency") { + this.addBuildDependency(message.file); + } + if (message.type === "asset" && message.content && message.file) { this.emitFile( message.file, diff --git a/test/__snapshots__/loader.test.js.snap b/test/__snapshots__/loader.test.js.snap index e63f9610..e26bce3e 100644 --- a/test/__snapshots__/loader.test.js.snap +++ b/test/__snapshots__/loader.test.js.snap @@ -106,6 +106,10 @@ Warning ] `; +exports[`loader should register dependencies using the "messages" API: errors 1`] = `Array []`; + +exports[`loader should register dependencies using the "messages" API: warnings 1`] = `Array []`; + exports[`loader should reuse PostCSS AST: css 1`] = ` "a { color: black; diff --git a/test/loader.test.js b/test/loader.test.js index 832d3880..10d41eee 100644 --- a/test/loader.test.js +++ b/test/loader.test.js @@ -1,6 +1,7 @@ import path from "path"; import postcss from "postcss"; +import { NormalModule } from "webpack"; import { compile, @@ -81,6 +82,54 @@ describe("loader", () => { expect(getErrors(stats)).toMatchSnapshot("errors"); }); + it('should register dependencies using the "messages" API', async () => { + const plugin = () => (css, result) => { + result.messages.push({ + type: "build-dependency", + file: "build-dep.html", + content: "", + plugin, + }); + }; + + let actualBuildInfo = null; + + const postcssPlugin = postcss.plugin("postcss-plugin", plugin); + const compiler = getCompiler( + "./css/index.js", + { + postcssOptions: { + plugins: [postcssPlugin()], + }, + }, + { + plugins: [ + { + /** @param {import("webpack").Compiler} compiler */ + apply(wpcompiler) { + wpcompiler.hooks.compilation.tap("plugin", (compilation) => { + NormalModule.getCompilationHooks(compilation).beforeLoaders.tap( + "plugin", + (_1, module) => { + actualBuildInfo = module.buildInfo; + } + ); + }); + }, + }, + ], + } + ); + + const stats = await compile(compiler); + + const buildDependencies = [...actualBuildInfo.buildDependencies]; + expect(buildDependencies).toContain("build-dep.html"); + + expect(getWarnings(stats)).toMatchSnapshot("warnings"); + expect(getErrors(stats)).toMatchSnapshot("errors"); + }); + it("should reuse PostCSS AST", async () => { const spy = jest.fn(); const compiler = getCompiler(