使import可以解析node内部模块
This commit is contained in:
parent
716a4bf526
commit
3ac1d92181
22
index.html
22
index.html
|
@ -6,6 +6,28 @@
|
|||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="viewport" content="user-scalable=no, viewport-fit=cover">
|
||||
<title>无名杀</title>
|
||||
<script>
|
||||
if (typeof window.require == 'function' &&
|
||||
typeof window.process == 'object' &&
|
||||
typeof window.__dirname == 'string') {
|
||||
// 使importMap解析node内置模块
|
||||
const builtinModules = require('module').builtinModules;
|
||||
if (Array.isArray(builtinModules)) {
|
||||
const importMap = {
|
||||
imports: {}
|
||||
};
|
||||
for (const module of builtinModules) {
|
||||
importMap.imports[module] =
|
||||
importMap.imports[`node:${module}`] =
|
||||
`./noname-builtinModules/${module}`
|
||||
}
|
||||
const im = document.createElement('script');
|
||||
im.type = 'importmap';
|
||||
im.textContent = JSON.stringify(importMap);
|
||||
document.currentScript.after(im);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
<script>
|
||||
"use strict";
|
||||
(() => {
|
||||
|
|
|
@ -59,11 +59,25 @@ self.addEventListener('fetch', event => {
|
|||
event.respondWith(rep);
|
||||
return;
|
||||
}
|
||||
if (!['.ts', '.json', '.vue', 'css'].some(ext => request.url.endsWith(ext))) return;
|
||||
if (!['.ts', '.json', '.vue', 'css'].some(ext => request.url.endsWith(ext)) && !request.url.replace(location.origin, '').startsWith('/noname-builtinModules/')) return;
|
||||
if (request.url.endsWith('.d.ts')) return;
|
||||
if (request.url.endsWith('.json') || request.url.endsWith('css')) {
|
||||
if (!event.request.headers.get('origin')) return;
|
||||
}
|
||||
if (request.url.replace(location.origin, '').startsWith('/noname-builtinModules/')) {
|
||||
const moduleName = request.url.replace(location.origin + '/noname-builtinModules/', '');
|
||||
console.log('正在编译', moduleName);
|
||||
let js = `const module = require('${ moduleName }');\nexport default module;`;
|
||||
const rep = new Response(new Blob([js], { type: "text/javascript" }), {
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
headers: new Headers({
|
||||
"Content-Type": "text/javascript"
|
||||
}),
|
||||
});
|
||||
console.log(moduleName, '编译成功');
|
||||
event.respondWith(Promise.resolve(rep));
|
||||
} else {
|
||||
// 请求原文件
|
||||
const res = fetch(request.url, {
|
||||
method: request.method,
|
||||
|
@ -201,4 +215,5 @@ self.addEventListener('fetch', event => {
|
|||
throw e;
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
Loading…
Reference in New Issue