我通过以下方式在打字稿中使用 Web Worker:
const url = new URL("src/lib/Functions/CalculateRidge.ts", import.meta.url);
const worker = new Worker(url, { type: 'module' })
在开发中,这项工作非常好,工作人员从给定的 url 加载,工作人员执行函数并给出正确的结果。但是在构建时,除我的工作文件外,所有文件都转换为 .js。然后在部署(Github Pages)中,当执行上面相同的代码时,url 请求成功(它找到文件并为它发出有效/成功的请求),但代码失败并显示以下错误消息:
“无法加载模块脚本:需要一个 JavaScript 模块脚本,但服务器以“video/mp2t”的 MIME 类型响应。根据 HTML 规范对模块脚本强制执行严格的 MIME 类型检查。”
我认为这个错误是因为无法执行或读取 typescript 文件(扩展名为 .ts 的文件),所以我认为错误在于 Web Worker typescript 文件没有被编译/转换为 Javascript。
这是分发/构建文件夹的图像:
我使用“vite build”构建项目,使用“npx gh-pages -d dist”将项目部署到 Github Pages。
vite.config.ts
文件如下所示:
import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'
import path from 'path';
// https://vitejs.dev/config/
export default defineConfig({
base: "/solar-analysis-faroe-island/",
plugins: [svelte()],
resolve: {
alias: {
src: path.resolve('src/'),
}
},
})
tsconfig.node.json
看起来像这样:
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "Node"
},
"include": ["vite.config.ts"]
}
tsconfig.json
看起来像这样:
{
"extends": "@tsconfig/svelte/tsconfig.json",
"compilerOptions": {
"baseUrl": ".",
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"resolveJsonModule": true,
"paths": {
"src/*": [
"src/*"
]
},
/**
* Typecheck JS in `.svelte` and `.js` files by default.
* Disable checkJs if you'd like to use dynamic types in JS.
* Note that setting allowJs false does not prevent the use
* of JS in `.svelte` files.
*/
"allowJs": true,
"checkJs": true,
"isolatedModules": true
},
"include": ["src/*.ts","src/**/*.d.ts", "src/**/*.ts", "src/**/*.js", "src/**/*.svelte"],
"references": [{ "path": "./tsconfig.node.json" }]
}
svelte.config.js
看起来像这样:
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'
export default {
// Consult https://svelte.dev/docs#compile-time-svelte-preprocess
// for more information about preprocessors
preprocess: vitePreprocess(),
}
会尝试不同的方式,让 Vite 生成这样的导入资产:
import workerUrl from "src/lib/Functions/CalculateRidge.ts?url";
const worker = new Worker(workerUrl, { type: 'module' })
(文档)
显然还有另一个输入工人的后缀:
import Worker from './shader.js?worker'
const worker = new Worker()