Merge pull request #919 from nonameShijian/PR-Branch

ts支持json导入
This commit is contained in:
Spmario233 2024-02-05 20:54:27 +08:00 committed by GitHub
commit d2641c9f97
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 29 additions and 9 deletions

View File

@ -123,7 +123,9 @@ new Promise(resolve => {
const result = ts.transpile(code, {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2019,
inlineSourceMap: true
inlineSourceMap: true,
resolveJsonModule: true,
esModuleInterop: true,
}, fileName);
// 使用默认的js编译函数获取返回值
return _compile.call(this, result, fileName);

View File

@ -10,7 +10,13 @@ if (typeof ts != 'undefined') {
console.log(`ts undefined`);
}
console.log('version 1');
console.log('version 2.1');
self.addEventListener("install", (event) => {
// The promise that skipWaiting() returns can be safely ignored.
// @ts-ignore
self.skipWaiting();
});
self.addEventListener('message', event => {
console.log(event.data);
@ -20,7 +26,12 @@ 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;
if (!['.ts', '.json'].some(ext => request.url.endsWith(ext))) return;
if (request.url.endsWith('.d.ts')) return;
if (request.url.endsWith('.json')) {
// @ts-ignore
if (!event.request.headers.get('origin')) return;
}
// 请求ts文件
const res = fetch(request.url, {
method: request.method,
@ -35,11 +46,18 @@ self.addEventListener('fetch', event => {
if (res.status != 200) return res;
console.log('正在编译', request.url);
return res.text().then(text => {
const js = ts.transpile(text, {
module: ts.ModuleKind.ES2015,
target: ts.ScriptTarget.ES2019,
inlineSourceMap: true
}, request.url);
let js;
if (request.url.endsWith('.json')) {
js = `export default ${text}`;
} else {
js = ts.transpile(text, {
module: ts.ModuleKind.ES2015,
target: ts.ScriptTarget.ES2019,
inlineSourceMap: true,
resolveJsonModule: true,
esModuleInterop: true,
}, request.url);
}
const rep = new Response(new Blob([js], { type: "text/javascript" }), {
status: 200,
statusText: "OK",

View File

@ -39,7 +39,7 @@
], /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
"resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */