首页 > 解决方案 > 如何在打字稿中导入three.js GLTFExporter?

问题描述

我正在尝试GLTFExporter在 three.js 打字稿项目中使用。我在https://github.com/pinqy520/three-typescript-starter使用示例启动器,并且只将这些行添加到render函数中:

console.log(`type of exporter = ${typeof(THREE.GLTFExporter)}`)
let exporter = new THREE.GLTFExporter()
exporter.parse(scene, (gltf) => {console.log("Parsed scene!"); }, {});

但是当我npm start在浏览器中运行它时,它THREE.GLTFExporter是未定义的,所以它“不是构造函数”(当然)。我怀疑这是因为 typescript 类型GLTFExporter是在中导出的,three-gltfexporter.d.ts但实际的类实际上并没有从它的源中导出node_modules/three/examples/js/exports/GLTFExporter.js(那里没有export关键字)。但是我对打字稿还是很陌生,所以可能是我不理解某些东西。但是 three.js 的所有“常规”部分都可以很好地导入,所以我怀疑仅在 .js 中GLTFExporter定义的事实examples/

标签: javascripttypescriptthree.js

解决方案


看起来您需要放入THREE全局范围,然后导入 GLTFExporter,因为 GLTFExporter 文件希望THREE在全局范围中找到以便添加:

(<any>window).THREE = THREE;
import "three/examples/js/exporters/GLTFExporter";

最好@types/three有一个单独的声明文件,其中three每个可选扩展都有一个模块扩充,GLTFExporter而不是无条件地声明所有可选扩展,这样 TypeScript 就能够在编译时警告你这个问题。考虑在DefinitiveTyped上提交一个错误。


推荐阅读