From 2167afc5e57bb65103467748d71bf3e04130e7e6 Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Wed, 29 Jan 2025 15:07:09 +0100 Subject: [PATCH] cli: treat static file assets as free from side-effects Signed-off-by: Patrik Oldsberg --- .changeset/fifty-trains-attend.md | 5 ++++ packages/cli/src/lib/builder/plugins.ts | 40 +++++++++++++++++++++++-- 2 files changed, 43 insertions(+), 2 deletions(-) create mode 100644 .changeset/fifty-trains-attend.md diff --git a/.changeset/fifty-trains-attend.md b/.changeset/fifty-trains-attend.md new file mode 100644 index 0000000000..04318409fd --- /dev/null +++ b/.changeset/fifty-trains-attend.md @@ -0,0 +1,5 @@ +--- +'@backstage/cli': patch +--- + +Treat static file assets as always being free from side effects in package builds. diff --git a/packages/cli/src/lib/builder/plugins.ts b/packages/cli/src/lib/builder/plugins.ts index 1c1dd1b1e2..ace2c048a9 100644 --- a/packages/cli/src/lib/builder/plugins.ts +++ b/packages/cli/src/lib/builder/plugins.ts @@ -21,7 +21,12 @@ import { relative as relativePath, } from 'path'; import { createFilter } from 'rollup-pluginutils'; -import { Plugin, InputOptions, OutputChunk } from 'rollup'; +import { + Plugin, + InputOptions, + OutputChunk, + HasModuleSideEffects, +} from 'rollup'; type ForwardFileImportsOptions = { include: Array | string | RegExp | null; @@ -91,6 +96,33 @@ export function forwardFileImports(options: ForwardFileImportsOptions) { } }, options(inputOptions) { + // We're in control of the config ourselves, so these are just checks to + // make sure we don't update the config but forget about the config + // overrides here + const treeshake = inputOptions.treeshake; + if (treeshake !== undefined && typeof treeshake !== 'object') { + throw new Error( + 'Expected treeshake input config to be an object or not set', + ); + } + if (treeshake?.moduleSideEffects) { + throw new Error('treeshake.moduleSideEffects must not be set'); + } + + // All external assets are treated as being side-effect free. + // + // This also works around an apparent bug in rollup where the + // `makeAbsoluteExternalsRelative: false` option sometimes caused relative + // asset paths to be rewritten with an incorrect path. They are rewritten + // in the first place because they are being treated as external by this + // plugin, but that seems to be the best way to handle asset files. + const moduleSideEffects: HasModuleSideEffects = id => { + if (filter(id)) { + return false; + } + return true; + }; + const origExternal = inputOptions.external; // We decorate any existing `external` option with our own way of determining @@ -129,7 +161,11 @@ export function forwardFileImports(options: ForwardFileImportsOptions) { return true; }; - return { ...inputOptions, external }; + return { + ...inputOptions, + external, + treeshake: { ...treeshake, moduleSideEffects }, + }; }, } satisfies Plugin; }