问题描述
我已经开发了一个伪造扩展名,现在我想在此博客文章.但是,我无法从全局Autodesk命名空间扩展原型,例如 Autodesk.Viewing.Extension
, Autodesk.Viewing.ToolInterface
,因为打字稿找不到对象找不到名称"Autodesk"
(在转换时不存在).目前,我的解决方法是通过调用创建扩展类的工厂函数来注入参数 Autodesk
(请参见代码示例),因为我无法从ES6模块内部访问全局Autodesk变量.这种解决方法自然会删除所有类型.
I have developed a forge extension and now I want to add typescript support following this blog post. However, I cannot extend the prototypes from the global Autodesk namespace like Autodesk.Viewing.Extension
, Autodesk.Viewing.ToolInterface
because typescript cannot find the objects Cannot find name 'Autodesk'
(which don't exist at transpile time). Currently my workaround is to inject a the parameter Autodesk
by calling a factory function which creates the Extension class (see code example) because I cannot access the global Autodesk variable from inside an ES6 module. This workaround removes all types naturally.
如何在自定义扩展程序中完全支持打字稿?
How can I fully support typescript in a custom extension?
function(Autodesk: any) { // injects Autodesk by passing the global accessible Autodesk object...
return class MyExtension extends Autodesk.Viewing.Extension {
...
};
}
我要实现的目标(支持打字稿):
class MyAwesomeExtension extends Autodesk.Viewing.Extension {
constructor(viewer, options) {
super(viewer, options);
}
load() {
console.log('MyAwesomeExtensions has been loaded');
viewer.setEnvMapBackground(null); // Hide background environment if there is one
viewer.setBackgroundColor(0, 64, 128); // Set background color
return true;
}
unload() {
console.log('MyAwesomeExtensions has been unloaded');
return true;
}
}
Autodesk.Viewing.theExtensionManager.registerExtension('MyAwesomeExtension', MyAwesomeExtension);
推荐答案
所以我的问题是我不知道如何从ES6模块访问全局库.但是,您可以使用 globalThis
从ES6模块内部访问全局变量.这样一来,您可以像平常一样使用类型.
So my problem was that I didn't know how to access the global libraries from an ES6 module. However, you can use globalThis
to access global variables from inside an ES6 module. That enables you to use typings like normally.
MyExtension.ts
MyExtension.ts
const Autodesk = globalThis.Autodesk;
const THREE = globalThis.THREE;
export class MyExtension extends Autodesk.Viewing.Extension {
//...
}
如果您将打字稿配置为允许umd访问,则不需要前两行(例如 const THREE = globalThis.THREE
):
The first two lines (e.g. const THREE = globalThis.THREE
) are not necessary if you configure typescript to allow umd access:
{
"compilerOptions": {
"allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
}
}
这篇关于在ES6模块内扩展对具有Typescript支持的`Autodesk.Viewing.Extension'之类的全局对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!