添加解析ts文件逻辑

This commit is contained in:
nonameShijian 2024-02-01 19:22:37 +08:00
parent 2766fbbad1
commit b0c0f70e57
3 changed files with 74 additions and 1 deletions

1
.gitignore vendored
View File

@ -28,3 +28,4 @@ noname.ico
package-lock.json package-lock.json
package.json package.json
Thumbs.db Thumbs.db
game/typescript.js

View File

@ -103,6 +103,21 @@ new Promise(resolve => {
} }
}; };
} }
if (location.protocol.startsWith('http') && 'serviceWorker' in navigator) {
let scope = window.location.protocol + '//' + window.location.host + '/';
navigator.serviceWorker.register(`${scope}service-worker.js`, {
updateViaCache: "all",
scope,
}).then(registration => {
navigator.serviceWorker.addEventListener('message', e => {
console.log(e);
});
registration.update();
// console.log(`set scope: ${scope}, service worker instance:`, registration);
}).catch(e => {
console.log('serviceWorker加载失败: ', e);
});
}
const script = document.createElement('script') const script = document.createElement('script')
script.type = "module"; script.type = "module";
script.src = `${assetURL}game/entry.js`; script.src = `${assetURL}game/entry.js`;

57
service-worker.js Normal file
View File

@ -0,0 +1,57 @@
/**
* @type { import('typescript') }
*/
var ts;
importScripts('./game/typescript.js');
// @ts-ignore
if (typeof ts != 'undefined') {
console.log(ts);
} else {
console.log(`ts undefined`);
}
console.log('version 1');
self.addEventListener('message', event => {
console.log(event.data);
});
self.addEventListener('fetch', event => {
// @ts-ignore
const request = event.request;
if (typeof request.url != 'string') return console.log(request);
if (!request.url.endsWith('.ts') || request.url.endsWith('.d.ts')) return;
// 请求ts文件
const res = fetch(request.url, {
method: request.method,
mode: "no-cors",
headers: new Headers({
"Content-Type": "text/plain"
}),
});
// @ts-ignore
event.respondWith(
res.then(res => {
if (res.status != 200) {
return res;
} else {
console.log('正在编译', request.url);
return res.text().then(text => {
const js = ts.transpile(text, { module: ts.ModuleKind.ES2015 });
const rep = new Response(new Blob([js], { type: "text/javascript" }), {
status: 200,
statusText: "OK",
headers: new Headers({
"Content-Type": "text/javascript"
}),
});
return rep;
})
}
})
.catch(e => {
console.log(e);
throw e;
})
);
});