I am using puppeteer and webpack in combination for a project. I compile my files into one bundle, and then using the addScriptTag method on puppeteer, adding that file to the browser. In addition, I am using the exposeFunction functionality so I can send/receive data from the browser to nodejs, more specifically, so I can make some database calls. My dilemma is that typescript does not recognize these functions, since they are never actually declared in my bundle, instead on the nodejs side, like so:
await page.exposeFunction("getPlayerFromDB", async (options) => {
// Some database call
return DB.players.get(options);
});
And then in my files I reference it like so:
const player = await getPlayerFromDB(options)
Of course that throws a typescript error of: "Cannot find name 'getPlayerFromDB'"
At first I just @ts-ignore, but as I have more of these exposedFunctions, and because the props for them are kind of complex, it would be nice to benefit from the autocompletion and typechecking of typescript. Therefore I found about the .d.ts files and declaring functions, however I ran into a whole more problems, which I will explain below.
- Problem with .d.ts files: Module not found
export declare function getPlayerFromDB(
options: Partial<Pick<Player, "name" | "auth" | "ip">>
): Promise<DBUser> | null;
and importing like:
import { getPlayerFromDB } from "../utils/puppeteer";
For reference, ../utilts/puppeteer is the file I am making all my exposeFunction function declarations.
I guess webpack cant find the .d.ts file? Even when I go in the compiler options and add the .d.ts extension, or I reference the import ending it with .d, it still cant find the module.
- Removed the .d.ts, extension and just sticking with .ts
Now typescript compiles, but my code doesn't work, I receive the error: "puppeteer_1.getPlayerFromDB) is not a function" Im guessing that this is because webpack is converting it to a module, but puppeteer expects just the function name.
So my question is how do I get around this? I can always just @ts-ignore every time I use one of the exposedFunctions OR I can just write the function declaration inside the file every time I use it, but that's not really practical.