chromeExtensionAsync icon indicating copy to clipboard operation
chromeExtensionAsync copied to clipboard

How can I import typedefs?

Open avalanche1 opened this issue 5 years ago • 2 comments

Namely, I need the def of async version of chrome.tabs.getCurrent(). When I try to import chrome from "chrome-extension-async/chrome-extension-async"; TS says node_modules/chrome-extension-async is not a module.

avalanche1 avatar Feb 24 '20 12:02 avalanche1

Was just figuring this out yesterday. This package is a wrapper written in JavaScript that provides a TypeScript definition file. In order to import definition files, you either import it into your code like this:

import "chrome-extension-async";

or by adding "chrome-extension-async" to your tsconfig.json, under compilerOptions.types, like so:

{
  "compilerOptions": {
    "types": [
      "chrome-extension-async"
    ],
    // other options
  }
}

and then you will have access to the chrome namespace and your code and types using chrome will appear correctly. Additionally if you only need access to one or a few APIs under chrome, you can use a namespace alias to alias that API to a shorter name.

import "chrome-extension-async";
chrome.storage.local.clear(); // the regular way

import storage = chrome.storage;
storage.local.clear(); // Now chrome.storage is accessible under storage

@KeithHenry Many popular packages are often imported as modules and not declarations and the TypeScript usage may not be obvious to some, so this may be worth putting in the README.

biggestcookie avatar Oct 14 '20 15:10 biggestcookie

@biggestcookie good idea! PRs welcome :) Otherwise I'll get round to it when I update the docs for the next release.

KeithHenry avatar Oct 14 '20 18:10 KeithHenry