forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvirtual-module-plugin.ts
83 lines (71 loc) · 2.03 KB
/
virtual-module-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
78
79
80
81
82
83
/**
* @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.dev/license
*/
import type { OnLoadArgs, Plugin, PluginBuild } from 'esbuild';
import { LoadResultCache, createCachedLoad } from './load-result-cache';
/**
* Options for the createVirtualModulePlugin
* @see createVirtualModulePlugin
*/
export interface VirtualModulePluginOptions {
/** Namespace. Example: `angular:polyfills`. */
namespace: string;
/** If the generated module should be marked as external. */
external?: boolean;
/** Method to transform the onResolve path. */
transformPath?: (path: string) => string;
/** Method to provide the module content. */
loadContent: (
args: OnLoadArgs,
build: PluginBuild,
) => ReturnType<Parameters<PluginBuild['onLoad']>[1]>;
/** Restrict to only entry points. Defaults to `true`. */
entryPointOnly?: boolean;
/** Load results cache. */
cache?: LoadResultCache;
}
/**
* Creates an esbuild plugin that generated virtual modules.
*
* @returns An esbuild plugin.
*/
export function createVirtualModulePlugin(options: VirtualModulePluginOptions): Plugin {
const {
namespace,
external,
transformPath: pathTransformer,
loadContent,
cache,
entryPointOnly = true,
} = options;
return {
name: namespace.replace(/[/:]/g, '-'),
setup(build): void {
build.onResolve({ filter: new RegExp('^' + namespace) }, ({ kind, path }) => {
if (entryPointOnly && kind !== 'entry-point') {
return null;
}
return {
path: pathTransformer?.(path) ?? path,
namespace,
};
});
if (external) {
build.onResolve({ filter: /./, namespace }, ({ path }) => {
return {
path,
external: true,
};
});
}
build.onLoad(
{ filter: /./, namespace },
createCachedLoad(cache, (args) => loadContent(args, build)),
);
},
};
}