Skip to content

Commit 24aaf1e

Browse files
committed
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.
1 parent 6f521fb commit 24aaf1e

File tree

3 files changed

+195
-0
lines changed

3 files changed

+195
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import { buildApplication } from '../../index';
10+
import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup';
11+
12+
describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => {
13+
describe('Behavior: "loader import attribute"', () => {
14+
beforeEach(async () => {
15+
await harness.modifyFile('tsconfig.json', (content) => {
16+
return content.replace('"module": "ES2022"', '"module": "esnext"');
17+
});
18+
});
19+
20+
it('should inline text content for loader attribute set to "text"', async () => {
21+
harness.useTarget('build', {
22+
...BASE_OPTIONS,
23+
});
24+
25+
await harness.writeFile('./src/a.unknown', 'ABC');
26+
await harness.writeFile(
27+
'src/main.ts',
28+
'// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "text" };\n console.log(contents);',
29+
);
30+
31+
const { result } = await harness.executeOnce();
32+
expect(result?.success).toBe(true);
33+
harness.expectFile('dist/browser/main.js').content.toContain('ABC');
34+
});
35+
36+
it('should inline binary content for loader attribute set to "binary"', async () => {
37+
harness.useTarget('build', {
38+
...BASE_OPTIONS,
39+
});
40+
41+
await harness.writeFile('./src/a.unknown', 'ABC');
42+
await harness.writeFile(
43+
'src/main.ts',
44+
'// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "binary" };\n console.log(contents);',
45+
);
46+
47+
const { result } = await harness.executeOnce();
48+
expect(result?.success).toBe(true);
49+
// Should contain the binary encoding used esbuild and not the text content
50+
harness.expectFile('dist/browser/main.js').content.toContain('__toBinary("QUJD")');
51+
harness.expectFile('dist/browser/main.js').content.not.toContain('ABC');
52+
});
53+
54+
it('should emit an output file for loader attribute set to "file"', async () => {
55+
harness.useTarget('build', {
56+
...BASE_OPTIONS,
57+
});
58+
59+
await harness.writeFile('./src/a.unknown', 'ABC');
60+
await harness.writeFile(
61+
'src/main.ts',
62+
'// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "file" };\n console.log(contents);',
63+
);
64+
65+
const { result } = await harness.executeOnce();
66+
expect(result?.success).toBe(true);
67+
harness.expectFile('dist/browser/main.js').content.toContain('a.unknown');
68+
harness.expectFile('dist/browser/media/a.unknown').toExist();
69+
});
70+
71+
it('should emit an output file with hashing when enabled for loader attribute set to "file"', async () => {
72+
harness.useTarget('build', {
73+
...BASE_OPTIONS,
74+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
75+
outputHashing: 'media' as any,
76+
});
77+
78+
await harness.writeFile('./src/a.unknown', 'ABC');
79+
await harness.writeFile(
80+
'src/main.ts',
81+
'// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "file" };\n console.log(contents);',
82+
);
83+
84+
const { result } = await harness.executeOnce();
85+
expect(result?.success).toBe(true);
86+
harness.expectFile('dist/browser/main.js').content.toContain('a.unknown');
87+
expect(harness.hasFileMatch('dist/browser/media', /a-[0-9A-Z]{8}\.unknown$/)).toBeTrue();
88+
});
89+
90+
it('should allow overriding default `.txt` extension behavior', async () => {
91+
harness.useTarget('build', {
92+
...BASE_OPTIONS,
93+
});
94+
95+
await harness.writeFile('./src/a.txt', 'ABC');
96+
await harness.writeFile(
97+
'src/main.ts',
98+
'// @ts-expect-error\nimport contents from "./a.txt" with { loader: "file" };\n console.log(contents);',
99+
);
100+
101+
const { result } = await harness.executeOnce();
102+
expect(result?.success).toBe(true);
103+
harness.expectFile('dist/browser/main.js').content.toContain('a.txt');
104+
harness.expectFile('dist/browser/media/a.txt').toExist();
105+
});
106+
107+
it('should allow overriding default `.js` extension behavior', async () => {
108+
harness.useTarget('build', {
109+
...BASE_OPTIONS,
110+
});
111+
112+
await harness.writeFile('./src/a.js', 'ABC');
113+
await harness.writeFile(
114+
'src/main.ts',
115+
'// @ts-expect-error\nimport contents from "./a.js" with { loader: "file" };\n console.log(contents);',
116+
);
117+
118+
const { result } = await harness.executeOnce();
119+
expect(result?.success).toBe(true);
120+
harness.expectFile('dist/browser/main.js').content.toContain('a.js');
121+
harness.expectFile('dist/browser/media/a.js').toExist();
122+
});
123+
124+
it('should fail with an error if an invalid loader attribute value is used', async () => {
125+
harness.useTarget('build', {
126+
...BASE_OPTIONS,
127+
});
128+
129+
harness.useTarget('build', {
130+
...BASE_OPTIONS,
131+
});
132+
133+
await harness.writeFile('./src/a.unknown', 'ABC');
134+
await harness.writeFile(
135+
'src/main.ts',
136+
'// @ts-expect-error\nimport contents from "./a.unknown" with { loader: "invalid" };\n console.log(contents);',
137+
);
138+
139+
const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false });
140+
expect(result?.success).toBe(false);
141+
expect(logs).toContain(
142+
jasmine.objectContaining({
143+
message: jasmine.stringMatching('Unsupported loader import attribute'),
144+
}),
145+
);
146+
});
147+
});
148+
});

packages/angular/build/src/tools/esbuild/application-code-bundle.ts

+3
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { BundlerOptionsFactory } from './bundler-context';
1919
import { createCompilerPluginOptions } from './compiler-plugin-options';
2020
import { createExternalPackagesPlugin } from './external-packages-plugin';
2121
import { createAngularLocaleDataPlugin } from './i18n-locale-plugin';
22+
import { createLoaderImportAttributePlugin } from './loader-import-attribute-plugin';
2223
import { createRxjsEsmResolutionPlugin } from './rxjs-esm-resolution-plugin';
2324
import { createSourcemapIgnorelistPlugin } from './sourcemap-ignorelist-plugin';
2425
import { getFeatureSupport, isZonelessApp } from './utils';
@@ -53,6 +54,7 @@ export function createBrowserCodeBundleOptions(
5354
target,
5455
supported: getFeatureSupport(target, zoneless),
5556
plugins: [
57+
createLoaderImportAttributePlugin(),
5658
createWasmPlugin({ allowAsync: zoneless, cache: sourceFileCache?.loadResultCache }),
5759
createSourcemapIgnorelistPlugin(),
5860
createCompilerPlugin(
@@ -210,6 +212,7 @@ export function createServerCodeBundleOptions(
210212
entryPoints,
211213
supported: getFeatureSupport(target, zoneless),
212214
plugins: [
215+
createLoaderImportAttributePlugin(),
213216
createWasmPlugin({ allowAsync: zoneless, cache: sourceFileCache?.loadResultCache }),
214217
createSourcemapIgnorelistPlugin(),
215218
createCompilerPlugin(
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import type { Loader, Plugin } from 'esbuild';
10+
import { readFile } from 'node:fs/promises';
11+
12+
const SUPPORTED_LOADERS: Loader[] = ['binary', 'file', 'text'];
13+
14+
export function createLoaderImportAttributePlugin(): Plugin {
15+
return {
16+
name: 'angular-loader-import-attributes',
17+
setup(build) {
18+
build.onLoad({ filter: /./ }, async (args) => {
19+
const loader = args.with['loader'] as Loader | undefined;
20+
if (!loader) {
21+
return undefined;
22+
}
23+
24+
if (!SUPPORTED_LOADERS.includes(loader)) {
25+
return {
26+
errors: [
27+
{
28+
text: 'Unsupported loader import attribute',
29+
notes: [
30+
{ text: 'Attribute value must be one of: ' + SUPPORTED_LOADERS.join(', ') },
31+
],
32+
},
33+
],
34+
};
35+
}
36+
37+
return {
38+
contents: await readFile(args.path),
39+
loader,
40+
};
41+
});
42+
},
43+
};
44+
}

0 commit comments

Comments
 (0)