问题描述
我已经开发了一个 forge 扩展,现在我想在 这篇博文.但是,我无法从全局 Autodesk 命名空间中扩展原型,例如 Autodesk.Viewing.Extension
、Autodesk.Viewing.ToolInterface
,因为 typescript 找不到对象 Cannot find name'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 {
//...
}
如果您将 typescript 配置为允许 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 模块内的打字稿支持扩展全局对象,如“Autodesk.Viewing.Extension"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!