From 24aaf1e37f49735ce97fe72fced3d53b51d6b631 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Thu, 11 Jul 2024 17:05:21 -0400 Subject: [PATCH] feat(@angular/build): support import attribute based loader configuration When using the application builder, a `loader` import attribute is now available for use with import statements and expressions. The presence of the import attribute takes precedence over all other loading behavior including JS/TS and any `loader` build option values. This allows per file control over loading behavior. For general loading for all files of an otherwise unsupported file type, the `loader` build option is recommended. For the import attribute, the following loader values are supported: * `text` - inlines the content as a string * `binary` - inlines the content as a Uint8Array * `file` - emits the file and provides the runtime location of the file Unfortunately, at this time, TypeScript does not support type definitions that are based on import attribute values. The use of `@ts-expect-error` or the use of individual type definition files (assuming the file is only imported with the same loader attribute) is currently required. Additionally, the TypeScript `module` option must be set to `esnext` to allow TypeScript to successfully build the application code. As an example, an SVG file can be imported as text via: ``` // @ts-expect-error TypeScript cannot provide types based on attributes yet import contents from './some-file.svg' with { loader: 'text' }; ``` When using the development server and a file that is referenced from a Node.js package with a loader attribute, the package must be excluded from prebundling via the development server `prebundle` option. This does not apply to relative file references. --- .../behavior/loader-import-attribute_spec.ts | 148 ++++++++++++++++++ .../tools/esbuild/application-code-bundle.ts | 3 + .../esbuild/loader-import-attribute-plugin.ts | 44 ++++++ 3 files changed, 195 insertions(+) create mode 100644 packages/angular/build/src/builders/application/tests/behavior/loader-import-attribute_spec.ts create mode 100644 packages/angular/build/src/tools/esbuild/loader-import-attribute-plugin.ts diff --git a/packages/angular/build/src/builders/application/tests/behavior/loader-import-attribute_spec.ts b/packages/angular/build/src/builders/application/tests/behavior/loader-import-attribute_spec.ts new file mode 100644 index 000000000000..2f360047b278 --- /dev/null +++ b/packages/angular/build/src/builders/application/tests/behavior/loader-import-attribute_spec.ts @@ -0,0 +1,148 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { buildApplication } from '../../index'; +import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; + +describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { + describe('Behavior: "loader import attribute"', () => { + beforeEach(async () => { + await harness.modifyFile('tsconfig.json', (content) => { + return content.replace('"module": "ES2022"', '"module": "esnext"'); + }); + }); + + it('should inline text content for loader attribute set to "text"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.unknown', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "text" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/main.js').content.toContain('ABC'); + }); + + it('should inline binary content for loader attribute set to "binary"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.unknown', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "binary" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + // Should contain the binary encoding used esbuild and not the text content + harness.expectFile('dist/browser/main.js').content.toContain('__toBinary("QUJD")'); + harness.expectFile('dist/browser/main.js').content.not.toContain('ABC'); + }); + + it('should emit an output file for loader attribute set to "file"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.unknown', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "file" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/main.js').content.toContain('a.unknown'); + harness.expectFile('dist/browser/media/a.unknown').toExist(); + }); + + it('should emit an output file with hashing when enabled for loader attribute set to "file"', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + outputHashing: 'media' as any, + }); + + await harness.writeFile('./src/a.unknown', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "file" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/main.js').content.toContain('a.unknown'); + expect(harness.hasFileMatch('dist/browser/media', /a-[0-9A-Z]{8}\.unknown$/)).toBeTrue(); + }); + + it('should allow overriding default `.txt` extension behavior', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.txt', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.txt" with { loader: "file" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/main.js').content.toContain('a.txt'); + harness.expectFile('dist/browser/media/a.txt').toExist(); + }); + + it('should allow overriding default `.js` extension behavior', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.js', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.js" with { loader: "file" };\n console.log(contents);', + ); + + const { result } = await harness.executeOnce(); + expect(result?.success).toBe(true); + harness.expectFile('dist/browser/main.js').content.toContain('a.js'); + harness.expectFile('dist/browser/media/a.js').toExist(); + }); + + it('should fail with an error if an invalid loader attribute value is used', async () => { + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + harness.useTarget('build', { + ...BASE_OPTIONS, + }); + + await harness.writeFile('./src/a.unknown', 'ABC'); + await harness.writeFile( + 'src/main.ts', + '// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "invalid" };\n console.log(contents);', + ); + + const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); + expect(result?.success).toBe(false); + expect(logs).toContain( + jasmine.objectContaining({ + message: jasmine.stringMatching('Unsupported loader import attribute'), + }), + ); + }); + }); +}); diff --git a/packages/angular/build/src/tools/esbuild/application-code-bundle.ts b/packages/angular/build/src/tools/esbuild/application-code-bundle.ts index b09a96d91361..6789c1e70c4a 100644 --- a/packages/angular/build/src/tools/esbuild/application-code-bundle.ts +++ b/packages/angular/build/src/tools/esbuild/application-code-bundle.ts @@ -19,6 +19,7 @@ import { BundlerOptionsFactory } from './bundler-context'; import { createCompilerPluginOptions } from './compiler-plugin-options'; import { createExternalPackagesPlugin } from './external-packages-plugin'; import { createAngularLocaleDataPlugin } from './i18n-locale-plugin'; +import { createLoaderImportAttributePlugin } from './loader-import-attribute-plugin'; import { createRxjsEsmResolutionPlugin } from './rxjs-esm-resolution-plugin'; import { createSourcemapIgnorelistPlugin } from './sourcemap-ignorelist-plugin'; import { getFeatureSupport, isZonelessApp } from './utils'; @@ -53,6 +54,7 @@ export function createBrowserCodeBundleOptions( target, supported: getFeatureSupport(target, zoneless), plugins: [ + createLoaderImportAttributePlugin(), createWasmPlugin({ allowAsync: zoneless, cache: sourceFileCache?.loadResultCache }), createSourcemapIgnorelistPlugin(), createCompilerPlugin( @@ -210,6 +212,7 @@ export function createServerCodeBundleOptions( entryPoints, supported: getFeatureSupport(target, zoneless), plugins: [ + createLoaderImportAttributePlugin(), createWasmPlugin({ allowAsync: zoneless, cache: sourceFileCache?.loadResultCache }), createSourcemapIgnorelistPlugin(), createCompilerPlugin( diff --git a/packages/angular/build/src/tools/esbuild/loader-import-attribute-plugin.ts b/packages/angular/build/src/tools/esbuild/loader-import-attribute-plugin.ts new file mode 100644 index 000000000000..2856ad5c4100 --- /dev/null +++ b/packages/angular/build/src/tools/esbuild/loader-import-attribute-plugin.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import type { Loader, Plugin } from 'esbuild'; +import { readFile } from 'node:fs/promises'; + +const SUPPORTED_LOADERS: Loader[] = ['binary', 'file', 'text']; + +export function createLoaderImportAttributePlugin(): Plugin { + return { + name: 'angular-loader-import-attributes', + setup(build) { + build.onLoad({ filter: /./ }, async (args) => { + const loader = args.with['loader'] as Loader | undefined; + if (!loader) { + return undefined; + } + + if (!SUPPORTED_LOADERS.includes(loader)) { + return { + errors: [ + { + text: 'Unsupported loader import attribute', + notes: [ + { text: 'Attribute value must be one of: ' + SUPPORTED_LOADERS.join(', ') }, + ], + }, + ], + }; + } + + return { + contents: await readFile(args.path), + loader, + }; + }); + }, + }; +}