-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathload-module.ts
54 lines (53 loc) · 1.5 KB
/
load-module.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
import type { AST } from "svelte-eslint-parser"
import Module from "module"
import path from "path"
import type { RuleContext } from "../types"
const cache = new WeakMap<AST.SvelteProgram, Record<string, unknown>>()
const cache4b = new Map<string, unknown>()
/**
* Load module
*/
export function loadModule<R>(context: RuleContext, name: string): R | null {
const key = context.getSourceCode().ast
let modules = cache.get(key)
if (!modules) {
modules = {}
cache.set(key, modules)
}
const mod = modules[name] || cache4b.get(name)
if (mod) return mod as R
try {
// load from cwd
const cwd = context.getCwd?.() ?? process.cwd()
const relativeTo = path.join(cwd, "__placeholder__.js")
return (modules[name] = Module.createRequire(relativeTo)(name) as R)
} catch {
// ignore
}
for (const relativeTo of [
// load from lint file name
context.getFilename(),
// load from lint file name (physical)
context.getPhysicalFilename?.(),
// load from this plugin module
typeof __filename !== "undefined" ? __filename : "",
]) {
if (relativeTo) {
try {
return (modules[name] = Module.createRequire(relativeTo)(name) as R)
} catch {
// ignore
}
}
}
return null
}
/** Load modules for browser */
export async function loadModulesForBrowser(): Promise<void> {
const [sass, typescript] = await Promise.all([
import("sass"),
import("typescript"),
])
cache4b.set("sass", sass)
cache4b.set("typescript", typescript)
}