Skip to content

Commit

Permalink
feat(@angular/build): support import attribute based loader configura…
Browse files Browse the repository at this point in the history
…tion

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.
  • Loading branch information
clydin committed Jul 15, 2024
1 parent 6f521fb commit 24aaf1e
Show file tree
Hide file tree
Showing 3 changed files with 195 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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'),
}),
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -53,6 +54,7 @@ export function createBrowserCodeBundleOptions(
target,
supported: getFeatureSupport(target, zoneless),
plugins: [
createLoaderImportAttributePlugin(),
createWasmPlugin({ allowAsync: zoneless, cache: sourceFileCache?.loadResultCache }),
createSourcemapIgnorelistPlugin(),
createCompilerPlugin(
Expand Down Expand Up @@ -210,6 +212,7 @@ export function createServerCodeBundleOptions(
entryPoints,
supported: getFeatureSupport(target, zoneless),
plugins: [
createLoaderImportAttributePlugin(),
createWasmPlugin({ allowAsync: zoneless, cache: sourceFileCache?.loadResultCache }),
createSourcemapIgnorelistPlugin(),
createCompilerPlugin(
Expand Down
Original file line number Diff line number Diff line change
@@ -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,
};
});
},
};
}

0 comments on commit 24aaf1e

Please sign in to comment.