我可以在HTML文件中的标记中设置importmap类型。但是web worker不能设置访问dom元素。我如何在其中设置importmap ?
我们已经通过ES垫片的小旁路完成了该方法(基于2022年11月4日发布的示例)。基本上,你启动一个worker,让它加载模块并读取这些。
我们使用这个项目在一个three.js场景中运行一个光线投射器,这个场景是不可见的,但通常应该可以工作。
workermanager.js:
let worker = new Worker('./workerloader.js');
worker.addEventListener("error", (e) => {
console.error("the worker died");
console.error(e);
})
worker.addEventListener("message", function(evt) {
let result = evt.data;
if (result === "loaded loader"){
console.log("loaded the workerloaded");
} else if (result === "Module worker Loaded")
worker.postMessage("Init Message");
else
console.log(`message from worker: `, evt);
});
workerloader.js
const shimCodeUrl = "https://ga.jspm.io/npm:es-module-shims@1.6.2/dist/es-module-shims.wasm.js"
const importMap = {
"imports": {
"three":"/whatever_path/three/build/three.module.js",
"three/":"/whatever_path/three/"
}
}
postMessage("loaded loader");
importScripts(shimCodeUrl);
importShim.addImportMap(importMap);
importShim("./worker.module.js") /*controllerworker.module.js*/
.then((res) => {
console.log("module has been loaded");
})
.catch(e => setTimeout(() => { throw e; }));
worker.module.js:
import * as THREE from "three";
class WorkerClass
{
constructor()
{
console.log(new THREE.Vector3(0,1,2));
}
onMessage(event)
{
console.log(event.data);
}
}
let workerclass = new WorkerClass();
self.addEventListener("message", evt => workerclass.onMessage(evt));
self.postMessage("Module worker Loaded");