I am trying to use optional module loading in Typescript for the webextension-polyfill-ts module.
I need to do so because I am building a library, using TypeScript, which must work on nodejs, browser and browser extension.
Unfortunately, underlying Mozilla's webextension-polyfill is throwing an error in non-WebExtension contexts.
Using TypeScript's optional loading, it throw an error, even if it should not load the module in the context.
Using try-catch block, I can't catch the error.
Here are samples:
Using optional loading
import * as Browser from "webextension-polyfill-ts";
let browser: any = false;
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
// eslint-disable-next-line prettier/prettier
if (typeof chrome !== "undefined" && chrome.runtime && chrome.runtime.id) {
browser = require("webextension-polyfill-ts");
} else {
console.log("a");
}
export default browser;
Using try-catch
let browser: any = null;
try {
browser = require("webextension-polyfill-ts");
} catch (e) {
console.log("a");
}
export default browser;
I found out why it didn't work. It was bound to tinyify. Simply removing its usage with browserify fixed the issue.