-
Notifications
You must be signed in to change notification settings - Fork 4
/
node-import-map-loader.js
51 lines (41 loc) · 1.28 KB
/
node-import-map-loader.js
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
import path from "path";
import { promises as fs } from "fs";
import {
resolveAndComposeImportMap,
resolveSpecifier,
} from "./import-map-utils.js";
let importMapPromise = getImportMapPromise();
export async function resolve(specifier, context, defaultResolve) {
const { parentURL = null } = context;
const importMap = await importMapPromise;
const importMapUrl = resolveSpecifier(importMap, specifier, parentURL);
return defaultResolve(importMapUrl ?? specifier, context, defaultResolve);
}
async function getImportMapPromise() {
const relativePath = process.env.IMPORT_MAP_PATH || "node.importmap";
const importMapPath = path.resolve(process.cwd(), relativePath);
let str;
try {
str = await fs.readFile(importMapPath);
} catch (err) {
return emptyMap();
}
let json;
try {
json = await JSON.parse(str);
} catch (err) {
throw Error(
`Import map at ${importMapPath} contains invalid json: ${err.message}`
);
}
return resolveAndComposeImportMap(json);
}
global.nodeLoader = global.nodeLoader || {};
global.nodeLoader.setImportMapPromise = function setImportMapPromise(promise) {
importMapPromise = promise.then((map) => {
return resolveAndComposeImportMap(map);
});
};
function emptyMap() {
return { imports: {}, scopes: {} };
}