From 06690d87eb590853eed6166857c9c1559d38d260 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Mon, 2 Dec 2024 18:34:05 -0500 Subject: [PATCH] fix(@angular/build): apply define option to JavaScript from scripts option The `define` option will now apply to JavaScript that is included in the output via the `scripts` option. This allows the replacement of identifiers within any included scripts in addition to the already supported replacement within application code. (cherry picked from commit 5bd937b86e96f715e19cdf3517691ba2dfd133c8) --- .../application/tests/options/define_spec.ts | 17 +++++++++++++++++ .../build/src/tools/esbuild/global-scripts.ts | 2 ++ 2 files changed, 19 insertions(+) diff --git a/packages/angular/build/src/builders/application/tests/options/define_spec.ts b/packages/angular/build/src/builders/application/tests/options/define_spec.ts index d4e3319553f2..ec8ccf2e6f24 100644 --- a/packages/angular/build/src/builders/application/tests/options/define_spec.ts +++ b/packages/angular/build/src/builders/application/tests/options/define_spec.ts @@ -61,5 +61,22 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { harness.expectFile('dist/browser/main.js').content.not.toContain('A_BOOLEAN'); harness.expectFile('dist/browser/main.js').content.toContain('(true)'); }); + + it('should replace a value in script code', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + define: { + 'A_BOOLEAN': 'true', + }, + scripts: ['./src/script.js'], + }); + + await harness.writeFile('src/script.js', 'console.log(A_BOOLEAN);'); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/scripts.js').content.not.toContain('A_BOOLEAN'); + harness.expectFile('dist/browser/scripts.js').content.toContain('(true)'); + }); }); }); diff --git a/packages/angular/build/src/tools/esbuild/global-scripts.ts b/packages/angular/build/src/tools/esbuild/global-scripts.ts index e69812d2fd30..1fb11a98a8eb 100644 --- a/packages/angular/build/src/tools/esbuild/global-scripts.ts +++ b/packages/angular/build/src/tools/esbuild/global-scripts.ts @@ -36,6 +36,7 @@ export function createGlobalScriptsBundleOptions( sourcemapOptions, jsonLogs, workspaceRoot, + define, } = options; const namespace = 'angular:script/global'; @@ -73,6 +74,7 @@ export function createGlobalScriptsBundleOptions( platform: 'neutral', target, preserveSymlinks, + define, plugins: [ createSourcemapIgnorelistPlugin(), createVirtualModulePlugin({