Skip to content

Commit 95284b9

Browse files
committed
feat(@angular-devkit/build-angular): allow configuring loaders for custom file extensions in application builder
When using the `application` builder, a new `loader` option is now available for use. The option allows a project to define the type of loader to use with a specified file extension. A file with the defined extension can then used within the application code via an import statement or dynamic import expression, for instance. The available loaders that can be used are: * `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 * `empty` - considers the content to be empty and will not include it in bundles The loader option is an object-based option with the keys used to define the file extension and the values used to define the loader type. An example to inline the content of SVG files into the bundled application would be as follows: ``` loader: { ".svg": "text" } ``` An SVG file can then be imported: ``` import contents from './some-file.svg'; ``` Additionally, TypeScript needs to be aware of the module type for the import to prevent type-checking errors during the build. This can be accomplished with an additional type definition file within the application source code (`src/types.d.ts`, for example) with the following or similar content: ``` declare module "*.svg" { const content: string; export default content; } ``` The default project configuration is already setup to use any type definition files present in the project source directories. If the TypeScript configuration for the project has been altered, the tsconfig may need to be adjusted to reference this newly added type definition file.
1 parent 10dbdac commit 95284b9

File tree

5 files changed

+284
-0
lines changed

5 files changed

+284
-0
lines changed

goldens/public-api/angular_devkit/build_angular/index.md

+3
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@ export interface ApplicationBuilderOptions {
3737
i18nMissingTranslation?: I18NTranslation_2;
3838
index: IndexUnion_2;
3939
inlineStyleLanguage?: InlineStyleLanguage_2;
40+
loader?: {
41+
[key: string]: any;
42+
};
4043
localize?: Localize_2;
4144
namedChunks?: boolean;
4245
optimization?: OptimizationUnion_2;

packages/angular_devkit/build_angular/src/builders/application/options.ts

+15
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,20 @@ export async function normalizeOptions(
143143
}
144144
}
145145

146+
let loaderExtensions: Record<string, 'text' | 'binary' | 'file'> | undefined;
147+
if (options.loader) {
148+
for (const [extension, value] of Object.entries(options.loader)) {
149+
if (extension[0] !== '.' || /\.[cm]?[jt]sx?$/.test(extension)) {
150+
continue;
151+
}
152+
if (value !== 'text' && value !== 'binary' && value !== 'file' && value !== 'empty') {
153+
continue;
154+
}
155+
loaderExtensions ??= {};
156+
loaderExtensions[extension] = value;
157+
}
158+
}
159+
146160
const globalStyles: { name: string; files: string[]; initial: boolean }[] = [];
147161
if (options.styles?.length) {
148162
const { entryPoints: stylesheetEntrypoints, noInjectNames } = normalizeGlobalStyles(
@@ -307,6 +321,7 @@ export async function normalizeOptions(
307321
budgets: budgets?.length ? budgets : undefined,
308322
publicPath: deployUrl ? deployUrl : undefined,
309323
plugins: plugins?.length ? plugins : undefined,
324+
loaderExtensions,
310325
};
311326
}
312327

packages/angular_devkit/build_angular/src/builders/application/schema.json

+7
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,13 @@
199199
}
200200
]
201201
},
202+
"loader": {
203+
"description": "Defines the type of loader to use with a specified file extension when used with a JavaScript `import`. `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; `empty` considers the content to be empty and not include it in bundles.",
204+
"type": "object",
205+
"patternProperties": {
206+
"^\\.\\S+$": { "enum": ["text", "binary", "file", "empty"] }
207+
}
208+
},
202209
"fileReplacements": {
203210
"description": "Replace compilation source files with other compilation source files in the build.",
204211
"type": "array",
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,257 @@
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.io/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('Option: "loader"', () => {
14+
it('should error for an unknown file extension', async () => {
15+
harness.useTarget('build', {
16+
...BASE_OPTIONS,
17+
});
18+
19+
await harness.writeFile(
20+
'./src/types.d.ts',
21+
'declare module "*.unknown" { const content: string; export default content; }',
22+
);
23+
await harness.writeFile('./src/a.unknown', 'ABC');
24+
await harness.writeFile(
25+
'src/main.ts',
26+
'import contents from "./a.unknown";\n console.log(contents);',
27+
);
28+
29+
const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false });
30+
expect(result?.success).toBe(false);
31+
expect(logs).toContain(
32+
jasmine.objectContaining({
33+
message: jasmine.stringMatching(
34+
'No loader is configured for ".unknown" files: src/a.unknown',
35+
),
36+
}),
37+
);
38+
});
39+
40+
it('should not include content for file extension set to "empty"', async () => {
41+
harness.useTarget('build', {
42+
...BASE_OPTIONS,
43+
loader: {
44+
'.unknown': 'empty',
45+
},
46+
});
47+
48+
await harness.writeFile(
49+
'./src/types.d.ts',
50+
'declare module "*.unknown" { const content: string; export default content; }',
51+
);
52+
await harness.writeFile('./src/a.unknown', 'ABC');
53+
await harness.writeFile(
54+
'src/main.ts',
55+
'import contents from "./a.unknown";\n console.log(contents);',
56+
);
57+
58+
const { result } = await harness.executeOnce();
59+
expect(result?.success).toBe(true);
60+
harness.expectFile('dist/browser/main.js').content.not.toContain('ABC');
61+
});
62+
63+
it('should inline text content for file extension set to "text"', async () => {
64+
harness.useTarget('build', {
65+
...BASE_OPTIONS,
66+
loader: {
67+
'.unknown': 'text',
68+
},
69+
});
70+
71+
await harness.writeFile(
72+
'./src/types.d.ts',
73+
'declare module "*.unknown" { const content: string; export default content; }',
74+
);
75+
await harness.writeFile('./src/a.unknown', 'ABC');
76+
await harness.writeFile(
77+
'src/main.ts',
78+
'import contents from "./a.unknown";\n console.log(contents);',
79+
);
80+
81+
const { result } = await harness.executeOnce();
82+
expect(result?.success).toBe(true);
83+
harness.expectFile('dist/browser/main.js').content.toContain('ABC');
84+
});
85+
86+
it('should inline binary content for file extension set to "binary"', async () => {
87+
harness.useTarget('build', {
88+
...BASE_OPTIONS,
89+
loader: {
90+
'.unknown': 'binary',
91+
},
92+
});
93+
94+
await harness.writeFile(
95+
'./src/types.d.ts',
96+
'declare module "*.unknown" { const content: Uint8Array; export default content; }',
97+
);
98+
await harness.writeFile('./src/a.unknown', 'ABC');
99+
await harness.writeFile(
100+
'src/main.ts',
101+
'import contents from "./a.unknown";\n console.log(contents);',
102+
);
103+
104+
const { result } = await harness.executeOnce();
105+
expect(result?.success).toBe(true);
106+
// Should contain the binary encoding used esbuild and not the text content
107+
harness.expectFile('dist/browser/main.js').content.toContain('__toBinary("QUJD")');
108+
harness.expectFile('dist/browser/main.js').content.not.toContain('ABC');
109+
});
110+
111+
it('should emit an output file for file extension set to "file"', async () => {
112+
harness.useTarget('build', {
113+
...BASE_OPTIONS,
114+
loader: {
115+
'.unknown': 'file',
116+
},
117+
});
118+
119+
await harness.writeFile(
120+
'./src/types.d.ts',
121+
'declare module "*.unknown" { const location: string; export default location; }',
122+
);
123+
await harness.writeFile('./src/a.unknown', 'ABC');
124+
await harness.writeFile(
125+
'src/main.ts',
126+
'import contents from "./a.unknown";\n console.log(contents);',
127+
);
128+
129+
const { result } = await harness.executeOnce();
130+
expect(result?.success).toBe(true);
131+
harness.expectFile('dist/browser/main.js').content.toContain('a.unknown');
132+
harness.expectFile('dist/browser/media/a.unknown').toExist();
133+
});
134+
135+
it('should emit an output file with hashing when enabled for file extension set to "file"', async () => {
136+
harness.useTarget('build', {
137+
...BASE_OPTIONS,
138+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
139+
outputHashing: 'media' as any,
140+
loader: {
141+
'.unknown': 'file',
142+
},
143+
});
144+
145+
await harness.writeFile(
146+
'./src/types.d.ts',
147+
'declare module "*.unknown" { const location: string; export default location; }',
148+
);
149+
await harness.writeFile('./src/a.unknown', 'ABC');
150+
await harness.writeFile(
151+
'src/main.ts',
152+
'import contents from "./a.unknown";\n console.log(contents);',
153+
);
154+
155+
const { result } = await harness.executeOnce();
156+
expect(result?.success).toBe(true);
157+
harness.expectFile('dist/browser/main.js').content.toContain('a.unknown');
158+
expect(harness.hasFileMatch('dist/browser/media', /a-[0-9A-Z]{8}\.unknown$/)).toBeTrue();
159+
});
160+
161+
it('should inline text content for `.txt` by default', async () => {
162+
harness.useTarget('build', {
163+
...BASE_OPTIONS,
164+
loader: undefined,
165+
});
166+
167+
await harness.writeFile(
168+
'./src/types.d.ts',
169+
'declare module "*.txt" { const content: string; export default content; }',
170+
);
171+
await harness.writeFile('./src/a.txt', 'ABC');
172+
await harness.writeFile(
173+
'src/main.ts',
174+
'import contents from "./a.txt";\n console.log(contents);',
175+
);
176+
177+
const { result } = await harness.executeOnce();
178+
expect(result?.success).toBe(true);
179+
harness.expectFile('dist/browser/main.js').content.toContain('ABC');
180+
});
181+
182+
it('should inline text content for `.txt` by default when other extensions are defined', async () => {
183+
harness.useTarget('build', {
184+
...BASE_OPTIONS,
185+
loader: {
186+
'.unknown': 'binary',
187+
},
188+
});
189+
190+
await harness.writeFile(
191+
'./src/types.d.ts',
192+
'declare module "*.txt" { const content: string; export default content; }',
193+
);
194+
await harness.writeFile('./src/a.txt', 'ABC');
195+
await harness.writeFile(
196+
'src/main.ts',
197+
'import contents from "./a.txt";\n console.log(contents);',
198+
);
199+
200+
const { result } = await harness.executeOnce();
201+
expect(result?.success).toBe(true);
202+
harness.expectFile('dist/browser/main.js').content.toContain('ABC');
203+
});
204+
205+
it('should allow overriding default `.txt` extension behavior', async () => {
206+
harness.useTarget('build', {
207+
...BASE_OPTIONS,
208+
loader: {
209+
'.txt': 'file',
210+
},
211+
});
212+
213+
await harness.writeFile(
214+
'./src/types.d.ts',
215+
'declare module "*.txt" { const location: string; export default location; }',
216+
);
217+
await harness.writeFile('./src/a.txt', 'ABC');
218+
await harness.writeFile(
219+
'src/main.ts',
220+
'import contents from "./a.txt";\n console.log(contents);',
221+
);
222+
223+
const { result } = await harness.executeOnce();
224+
expect(result?.success).toBe(true);
225+
harness.expectFile('dist/browser/main.js').content.toContain('a.txt');
226+
harness.expectFile('dist/browser/media/a.txt').toExist();
227+
});
228+
229+
// Schema validation will prevent this from happening for supported use-cases.
230+
// This will only happen if used programmatically and the option value is set incorrectly.
231+
it('should ignore entry if an invalid loader name is used', async () => {
232+
harness.useTarget('build', {
233+
...BASE_OPTIONS,
234+
loader: {
235+
'.unknown': 'invalid',
236+
},
237+
});
238+
239+
const { result } = await harness.executeOnce();
240+
expect(result?.success).toBe(true);
241+
});
242+
243+
// Schema validation will prevent this from happening for supported use-cases.
244+
// This will only happen if used programmatically and the option value is set incorrectly.
245+
it('should ignore entry if an extension does not start with a period', async () => {
246+
harness.useTarget('build', {
247+
...BASE_OPTIONS,
248+
loader: {
249+
'unknown': 'text',
250+
},
251+
});
252+
253+
const { result } = await harness.executeOnce();
254+
expect(result?.success).toBe(true);
255+
});
256+
});
257+
});

packages/angular_devkit/build_angular/src/tools/esbuild/application-code-bundle.ts

+2
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,7 @@ function getEsBuildCommonOptions(options: NormalizedApplicationBuildOptions): Bu
320320
outputNames,
321321
preserveSymlinks,
322322
jit,
323+
loaderExtensions,
323324
} = options;
324325

325326
// Ensure unique hashes for i18n translation changes when using post-process inlining.
@@ -367,6 +368,7 @@ function getEsBuildCommonOptions(options: NormalizedApplicationBuildOptions): Bu
367368
...(optimizationOptions.scripts ? { 'ngDevMode': 'false' } : undefined),
368369
'ngJitMode': jit ? 'true' : 'false',
369370
},
371+
loader: loaderExtensions,
370372
footer,
371373
publicPath: options.publicPath,
372374
};

0 commit comments

Comments
 (0)