Dear StackOverflow users,
I made a module for both browser and WeChat mini program.
That module is written in multiple TypeScript and is compiled to one minified file.
In that module, I need to use DOM/BOM APIs such as document
, 'window, 'navigator
.
On the browser, loading and using the compiled single-file have no problem.
But on the WeChat mini-program, there's no global
object as on Node. Nor there's no document
and window
global objects as on browser.
To fix this, I made two build commands for each environment.
grunt build
, standard TS compilation for browsergrunt wx_build
, standard TS compilation and append patch code for WeChat mini programThe patched js file looks like:
// 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")...
On WeChat mini program project, I put mymodule-bundle.min.js
and miniapp-adapter
in the same folder. As a result, I could port my HTML5 app to WeChat mini program.
But I want a smarter way to do that.
How can I declare the
window
ordocument
global variable inmymodule.ts
for WeChat mini-program runtime?
Thank you.
Here is how you declare them:
declare const document: any
declare const window: any
To get better types on them for intellisense you just make them of the type that represents what you have put there, if you need consumers to use them. Otherwise you can leave them like that.
In Node you can do this:
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;
To be idiomatic on Node, though, you should export them from a module, rather than loading them into the global namespace.