亲爱的StackOverflow用户:
我为浏览器和WeChat小程序开发了一个模块。该模块用多个TypeScript编写,并编译成一个缩小的文件。在这个模块中,我需要使用DOM/BOM API,比如document,'window, 'navigator。在浏览器上,加载和使用编译的单个文件没有问题。
但是在WeChat迷你程序中,没有global对象和Node一样.浏览器上也没有document和window全局对象。为了解决这个问题,我为每个环境创建了两个构建命令。
grunt build,标准TS编译browsergrunt wx_build,标准TS编译和附加WeChat小程序补丁代码
修补的js文件如下所示:
// mymodule-bundle.min.js
// patch
window=require("./miniapp-adapter/src/index.js");
document=require("./miniapp-adapter/src/document.js").default;
// original compiled/minified code
(function(f){if(typeof exports==="object"&&typeof module!=="undefined")...在WeChat小程序项目中,我把mymodule-bundle.min.js和miniapp-adapter放在同一个文件夹中。因此,我可以将我的HTML5应用程序移植到WeChat小程序。
但我想找个更聪明的方法。
如何在document mymodule.ts 中为WeChat迷你程序运行时声明mymodule.ts或document全局变量?
谢谢。
发布于 2020-02-22 02:59:15
以下是您如何声明它们的方法:
declare const document: any
declare const window: any要获得更好的intellisense类型,您只需使它们的类型代表您在那里放置的内容,如果您需要消费者使用它们。否则你就可以就这样离开他们了。
在Node中,您可以这样做:
declare namespace NodeJS {
export interface Global {
window: any
document: any
}
}
global.window = require("./miniapp-adapter/src/index.js");
global.document = require("./miniapp-adapter/src/document.js").default;不过,要想在Node上具有惯用性,您应该从模块导出它们,而不是将它们加载到全局命名空间中。
https://stackoverflow.com/questions/60348459
复制相似问题