问题描述
我正在为现有的Javascript应用程序编写插件- Forge Autodesk .查看
I am writing a plugin for existing Javascript app - Forge Autodesk.Viewing
第6版之后,他们将THREE.js包含在其应用包中.
After version 6 they have included THREE.js inside of their app bundle.
现在,我可以将其与我的插件一起使用,如下所示:
Right now I'm able to use it with my plugin like this:
declare var THREE:any;
但是我松了所有类型.
But I'm loose all types.
所以,我要通过
npm install --save three
我可以使用三个,并将其导入.但是我不需要导入它,因为我已经在主应用程序中将其导入了.我需要做的是引用类型.
I'm able to use THREE, and import it. But I don't need to Import it as I already have it in my main app. What I need to do is to reference types.
所以,我试图做这样的事情:
So, I tried to do something like this:
declare var THREE:THREE;
//Cannot use namespace 'THREE' as a type.
然后我尝试:
/// <reference types='three' />
可以正常工作,但是:
/// <reference types='three' />
which works fine, but:
const planes:THREE.Plane[] = []; //this line is okey
planes.push(new THREE.Plane()); //but this says
//'THREE' refers to a UMD global,
// but the current file is a module.
// Consider adding an import instead.
Tsc坚持我们应该导入它:
Tsc insist that we should import it:
import * as THREE from 'three';
它可以编译,没有任何问题,但是当我启动应用程序时,它崩溃了,原因是它试图获取THREE.js的另一个实例,我不提供该实例,因为我将它放在主应用程序中.
It's compile without any issues, but when I launch app it crash, cause it's try to get one more instance of THREE.js, which I do not provide cause I have it inside main app.
因此,总而言之-如何声明正确的引用并将类型保留为主要javascript应用程序可用的命名空间?
So to sum up - how to declare correct reference and keep types to an namespace which is available at main javascript application?
推荐答案
如果遇到以下问题:
'THREE' refers to a UMD global, but the current file is a module. Consider adding an import instead.
您可以尝试使用 tsconfig.json 中的选项:
You may try to use option in tsconfig.json:
"compilerOptions": {
"allowUmdGlobalAccess": true,
这将使编译器可以全局访问UMD,因此在这种情况下,您无需导入或引用此类模块.
This will give compiler access to UMD global, so you do not need to import or reference such modules in that case.
Three.js就是这种情况.它们确实将三个命名空间作为模块添加到UMD全局范围.因此,如果您需要包括此模块,则应该导入.如果只希望引用,则可以使用此选项.如果打字稿无法在配置中识别此选项,只需更新您的打字稿即可.
And it's exact the case with three.js They alredy add THREE namespace as module to UMD global scope. So if you need to include this module you should import. If you want only reference you could use this option. If typescript doesn't recognize this option in config just update your typescript.
npm install typescript
感谢亲爱的SalientBrain和亲爱的Petr Broz的关注和帮助.
Thank you dear SalientBrain and dear Petr Broz for your attention and help.
这篇关于如何声明对现有命名空间的引用,该命名空间在运行时可从javacript捆绑包获得的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!