|
| 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 } from 'esbuild'; |
| 10 | +import { extname } from 'node:path'; |
| 11 | + |
| 12 | +const EXTERNAL_PACKAGE_RESOLUTION = Symbol('EXTERNAL_PACKAGE_RESOLUTION'); |
| 13 | + |
| 14 | +/** |
| 15 | + * Creates a plugin that marks any resolved path as external if it is within a node modules directory. |
| 16 | + * This is used instead of the esbuild `packages` option to avoid marking files that should be loaded |
| 17 | + * via customized loaders. This is necessary to prevent Vite development server pre-bundling errors. |
| 18 | + * |
| 19 | + * @returns An esbuild plugin. |
| 20 | + */ |
| 21 | +export function createExternalPackagesPlugin(): Plugin { |
| 22 | + return { |
| 23 | + name: 'angular-external-packages', |
| 24 | + setup(build) { |
| 25 | + // Safe to use native packages external option if no loader options present |
| 26 | + if ( |
| 27 | + build.initialOptions.loader === undefined || |
| 28 | + Object.keys(build.initialOptions.loader).length === 0 |
| 29 | + ) { |
| 30 | + build.initialOptions.packages = 'external'; |
| 31 | + |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + const loaderFileExtensions = new Set(Object.keys(build.initialOptions.loader)); |
| 36 | + |
| 37 | + // Only attempt resolve of non-relative and non-absolute paths |
| 38 | + build.onResolve({ filter: /^[^./]/ }, async (args) => { |
| 39 | + if (args.pluginData?.[EXTERNAL_PACKAGE_RESOLUTION]) { |
| 40 | + return null; |
| 41 | + } |
| 42 | + |
| 43 | + const { importer, kind, resolveDir, namespace, pluginData = {} } = args; |
| 44 | + pluginData[EXTERNAL_PACKAGE_RESOLUTION] = true; |
| 45 | + |
| 46 | + const result = await build.resolve(args.path, { |
| 47 | + importer, |
| 48 | + kind, |
| 49 | + namespace, |
| 50 | + pluginData, |
| 51 | + resolveDir, |
| 52 | + }); |
| 53 | + |
| 54 | + // Return result if unable to resolve or explicitly marked external (externalDependencies option) |
| 55 | + if (!result.path || result.external) { |
| 56 | + return result; |
| 57 | + } |
| 58 | + |
| 59 | + // Allow customized loaders to run against configured paths regardless of location |
| 60 | + if (loaderFileExtensions.has(extname(result.path))) { |
| 61 | + return result; |
| 62 | + } |
| 63 | + |
| 64 | + // Mark paths from a node modules directory as external |
| 65 | + if (/[\\/]node_modules[\\/]/.test(result.path)) { |
| 66 | + return { |
| 67 | + path: args.path, |
| 68 | + external: true, |
| 69 | + }; |
| 70 | + } |
| 71 | + |
| 72 | + // Otherwise return original result |
| 73 | + return result; |
| 74 | + }); |
| 75 | + }, |
| 76 | + }; |
| 77 | +} |
0 commit comments