|
| 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 type { Plugin, PluginBuild } from 'esbuild'; |
| 10 | +import { readFile } from 'fs/promises'; |
| 11 | + |
| 12 | +/** |
| 13 | + * Symbol marker used to indicate CSS resource resolution is being attempted. |
| 14 | + * This is used to prevent an infinite loop within the plugin's resolve hook. |
| 15 | + */ |
| 16 | +const CSS_RESOURCE_RESOLUTION = Symbol('CSS_RESOURCE_RESOLUTION'); |
| 17 | + |
| 18 | +/** |
| 19 | + * Creates an esbuild {@link Plugin} that loads all CSS url token references using the |
| 20 | + * built-in esbuild `file` loader. A plugin is used to allow for all file extensions |
| 21 | + * and types to be supported without needing to manually specify all extensions |
| 22 | + * within the build configuration. |
| 23 | + * |
| 24 | + * @returns An esbuild {@link Plugin} instance. |
| 25 | + */ |
| 26 | +export function createCssResourcePlugin(): Plugin { |
| 27 | + return { |
| 28 | + name: 'angular-css-resource', |
| 29 | + setup(build: PluginBuild): void { |
| 30 | + build.onResolve({ filter: /.*/ }, async (args) => { |
| 31 | + // Only attempt to resolve url tokens which only exist inside CSS. |
| 32 | + // Also, skip this plugin if already attempting to resolve the url-token. |
| 33 | + if (args.kind !== 'url-token' || args.pluginData?.[CSS_RESOURCE_RESOLUTION]) { |
| 34 | + return null; |
| 35 | + } |
| 36 | + |
| 37 | + const { importer, kind, resolveDir, namespace, pluginData = {} } = args; |
| 38 | + pluginData[CSS_RESOURCE_RESOLUTION] = true; |
| 39 | + |
| 40 | + const result = await build.resolve(args.path, { |
| 41 | + importer, |
| 42 | + kind, |
| 43 | + namespace, |
| 44 | + pluginData, |
| 45 | + resolveDir, |
| 46 | + }); |
| 47 | + |
| 48 | + return { |
| 49 | + ...result, |
| 50 | + namespace: 'css-resource', |
| 51 | + }; |
| 52 | + }); |
| 53 | + |
| 54 | + build.onLoad({ filter: /.*/, namespace: 'css-resource' }, async (args) => { |
| 55 | + return { |
| 56 | + contents: await readFile(args.path), |
| 57 | + loader: 'file', |
| 58 | + }; |
| 59 | + }); |
| 60 | + }, |
| 61 | + }; |
| 62 | +} |
0 commit comments