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