-
Notifications
You must be signed in to change notification settings - Fork 0
/
unpkg-path-plugin.ts
61 lines (56 loc) · 1.84 KB
/
unpkg-path-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
import * as esbuild from 'esbuild-wasm';
import localForage from 'localforage';
const cache = localForage.createInstance({
name: 'fileCache'
});
export const unpkgPathPlugin = (inputCode: string) => {
return {
name: 'unpkg-path-plugin',
setup(build: esbuild.PluginBuild) {
// Override esbuild's default resolve to find the path
// of the index.js file
// Runs a second time where imports are
build.onResolve({ filter: /.*/ }, async (args: any) => {
const { path, resolveDir } = args;
if (path === 'index.js') {
return { path, namespace: 'a' }
// if the path is a relative path, create the correct url
} else if (path.includes('./') || path.includes('../')) {
return {
namespace: 'a',
path: new URL(path, `https://unpkg.com${resolveDir}/`).href
}
}
return {
namespace: 'a',
path: `https://unpkg.com/${path}`
}
});
// Override esbuild's default for reading the index.js directly
// from the file system
// Runs a second time to try to load the import file
build.onLoad({ filter: /.*/ }, async (args: any) => {
if (args.path === 'index.js') {
return {
loader: 'jsx',
contents: inputCode,
};
}
// Check to see if this exists in the cache
const cachedResult = await cache.getItem(args.path);
if (cachedResult) {
return cachedResult;
}
const response = await fetch(args.path);
const data = await response.text();
const result = {
loader: 'jsx',
contents: data,
resolveDir: new URL('./', response.url).pathname
};
await cache.setItem(args.path, result);
return result;
});
},
};
};