如何声明对现有名称空间的引用,该名称空间可在运行时从JavaScript捆绑包获得 [英] How to declare reference to an existing namespace which is available from JavaScript bundle at runtime

查看:78
本文介绍了如何声明对现有名称空间的引用,该名称空间可在运行时从JavaScript捆绑包获得的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为现有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; 

但是我丢失了所有类型,因此我通过以下方式安装three.js:

but I lose all types, so I install three.js by:

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' /> 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 insists that we should import it:

import * as THREE from 'three'; 

它可以编译,没有任何问题,但是当我启动该应用程序时,它崩溃了,因为它试图获取THREE.js的另一个实例,由于我将其放在主应用程序中,所以我不提供该实例.

It compiles without any issues, but when I launch the app it crash, because it's trying to get one more instance of THREE.js, which I do not provide because I have it inside main app.

如何声明正确的引用并保持对主要JavaScript应用程序可用的命名空间的类型?

How to declare the 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.

(关于UMD)

您可以尝试使用 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.

这篇关于如何声明对现有名称空间的引用,该名称空间可在运行时从JavaScript捆绑包获得的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆