Set deno.json
as follows so that the dom type can be resolved.
"compilerOptions": {
"lib": [
"deno.window",
"dom"
],
}
In some cases, additional options may need to be specified. Please refer to the following documentation for more information.
https://deno.land/manual@v1.28.3/advanced/typescript/configuration#targeting-deno-and-the-browser
In my case, I specify deno.window
because I am using it in a build script, but it is not necessary if it is just web extension code.
It would be better to use webextension-polyfill. This library is a polyfill to absorb differences between browsers. It also provides type definitions, which is useful.
import browser from "https://esm.sh/webextension-polyfill@0.10.0";
browser.commands.onCommand.addListener((command) => {
browser.tabs.create({ url: "https://developer.mozilla.org" });
});
If you do not use polyfill, you must resolve the chrome
global type if Chrome.
To resolve the chrome
type, the following type definitions published by NPM are available.
@types/chrome
seems to be used more, but chrome-types
is maintained by the Chrome team. Please read their descriptions for details.
Because chrome
is a global type, it uses a different method of defining type references than import does.
/// <reference types="npm:chrome-types/index.d.ts" />
chrome.commands.onCommand.addListener((command) => {
console.log(`Command "${command}" triggered`);
});
See Deno official document Using ambient or global types for more information. The documentation describes other methods.
If you want to refer to webextension-polyfill by npm identifier, you can probably do the following, but I got an error when I bound it. (deno v1.28.3)
// @deno-types="npm:@types/webextension-polyfill@0.9.2"
import browser from "npm:webextension-polyfill@0.10.0";
browser.commands.onCommand.addListener((command) => {
browser.tabs.create({ url: "https://developer.mozilla.org" });
});
error: Uncaught Error: Unable to output during bundling.
const ret = new Error(getStringFromWasm0(arg0, arg1));
^
at __wbg_new_651776e932b7e9c7 (https://deno.land/x/emit@0.11.0/lib/emit.generated.js:329:19)
at <anonymous> (https://deno.land/x/emit@0.11.0/lib/emit_bg.wasm:1:7177226)
at <anonymous> (https://deno.land/x/emit@0.11.0/lib/emit_bg.wasm:1:1486344)
at <anonymous> (https://deno.land/x/emit@0.11.0/lib/emit_bg.wasm:1:6221933)
at <anonymous> (https://deno.land/x/emit@0.11.0/lib/emit_bg.wasm:1:7136135)
at __wbg_adapter_16 (https://deno.land/x/emit@0.11.0/lib/emit.generated.js:205:6)
at real (https://deno.land/x/emit@0.11.0/lib/emit.generated.js:189:14)
If you use the minify version of webextension-polyfill
in esm.sh, type definitions are not automatically loaded, so specify the following.
// @deno-types="npm:@types/webextension-polyfill@0.9.2"
import browser from "https://esm.sh/webextension-polyfill@0.10.0/dist/browser-polyfill.min";