-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
replaceWithPlugin.ts
39 lines (33 loc) · 1.16 KB
/
replaceWithPlugin.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
import { builtinModules } from 'module'
import type * as esbuild from 'esbuild'
import fs from 'fs'
type Replacement = [RegExp, string | ((regex: RegExp, contents: string) => string | Promise<string>)]
async function applyReplacements(contents: string, replacements: Replacement[]) {
for (const [regex, replacement] of replacements) {
if (typeof replacement === 'string') {
contents = contents.replace(regex, replacement)
} else {
contents = await replacement(regex, contents)
}
}
return contents
}
/**
* Replace the contents of a file with the given replacements.
* @param replacements
* @returns
*/
export const replaceWithPlugin = (replacements: Replacement[]): esbuild.Plugin => {
return {
name: 'replaceWithPlugin',
setup(build) {
build.onLoad({ filter: /.*/ }, async (args) => {
// we skip, don't attempt to edit files that aren't js
if (builtinModules.includes(args.path)) return {}
if (!/.*?(.js|.mjs)$/.exec(args.path)) return {}
const contents = await fs.promises.readFile(args.path, 'utf8')
return { contents: await applyReplacements(contents, replacements) }
})
},
}
}