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

查看:35
本文介绍了如何声明对现有命名空间的引用,该命名空间在运行时可从 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.

然后我尝试:

/// 工作正常,但是:

        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天全站免登陆