Skip to content

Commit

Permalink
feat: plugin can be positioned anywhere in the plugins list
Browse files Browse the repository at this point in the history
  • Loading branch information
recursive-beast committed Feb 27, 2021
1 parent 89a8020 commit a7f1a89
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 16 deletions.
26 changes: 26 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,32 @@ export default function externalAssets(pattern: FilterPattern, options?: PluginO

return {
name: PLUGIN_NAME,
async options(inputOptions) {
const plugins = inputOptions.plugins;

// No transformations.
if (!plugins) return null;

// Separate our plugin from other plugins.
const externalAssetsPlugins: Plugin[] = [];
const otherPlugins = plugins.filter(plugin => {
if (plugin.name !== PLUGIN_NAME) return true;

externalAssetsPlugins.push(plugin);
return false;
});

// Re-position our plugin to be the first in the list.
// Otherwise, if there's a plugin that resolves paths before ours,
// non-external imports can trigger the load hook for assets that can't be parsed by other plugins.
return {
...inputOptions,
plugins: [
...externalAssetsPlugins,
...otherPlugins,
],
}
},
async resolveId(source, importer) {
// Skip resolving entrypoints,
// and don't resolve imports from filtered out modules.
Expand Down
31 changes: 15 additions & 16 deletions tests/general.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const test = require("ava");
const { nodeResolve } = require("@rollup/plugin-node-resolve");
const { bundleThrowsMacro } = require("./macros");
const { rollup } = require("rollup");
const externalAssets = require("..");

const falsy = [undefined, null, false, "", NaN, 0];
Expand All @@ -15,18 +15,17 @@ for (const value of falsy) {
});
}

// If there's a plugin that resolves paths before ours, non-external imports trigger the load hook.
test("Plugin doesn't work if it's not the first in the list", bundleThrowsMacro,
{
input: "tests/fixtures/src/index2.js",
plugins: [
nodeResolve({
moduleDirectories: ["tests/fixtures/node_modules"],
}),
externalAssets(["tests/fixtures/assets/*", /@fontsource\/open-sans/]),
],
},
{
code: "PARSE_ERROR",
},
);
// Solved by re-positioning the plugin to be the first on the list.
test("Plugin works even if it's not the first in the list", async t => {
await t.notThrowsAsync(
rollup({
input: "tests/fixtures/src/index2.js",
plugins: [
nodeResolve({
moduleDirectories: ["tests/fixtures/node_modules"],
}),
externalAssets(["tests/fixtures/assets/*", /@fontsource\/open-sans/]),
],
})
);
});

0 comments on commit a7f1a89

Please sign in to comment.