Using chrome extension apis in typescript

前端 未结 5 1551
广开言路
广开言路 2021-01-30 09:17

I\'m building a chrome extension written in TypeScript. I\'m using WebStorm and I added the chrome-DefiniteltyTyped library in my project.

However, when I w

相关标签:
5条回答
  • 2021-01-30 09:32

    You just need to install Type definition to make it work, let's install it:

    yarn add @types/chrome --dev
    

    or NPM

    npm install @types/chrome --save-dev
    

    now use free of error!

    0 讨论(0)
  • 2021-01-30 09:39

    I just ran into the below error when trying to develop a Chrome extension using TypeScript in VS Code and all I had to do was simply run:

    npm install --save-dev @types/chrome

    This will enter "@types/chrome": "0.0.120" under "devDependencies" in your package.json file.

    Fixed error:

    [tsl] ERROR in C:\Users\my_user\Documents\my_chrome_extension\src\content.ts(28,3) TS2304: Cannot find name 'chrome'.
    0 讨论(0)
  • 2021-01-30 09:50

    That should work fine : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/chrome/index.d.ts

    TIP: make sure you have a reference tag added:

    /// <reference path="pathTo/chrome.d.ts"/>

    0 讨论(0)
  • 2021-01-30 09:58

    Types Across Chrome and Firefox

    Since the extension API is basically the same across Chrome and Firefox now, you can use @types/chrome for both situations.

    1. install

    yarn add @types/chrome --dev
    

    2. update tsconfig

    {
      "compilerOptions": {
        ....
        "types": ["chrome"]
      }
    }
    

    3. Get browser api function

    export function getBrowserInstance(): typeof chrome {
      // Get extension api Chrome or Firefox
      const browserInstance = window.chrome || (window as any)['browser'];
      return browserInstance;
    }
    
    0 讨论(0)
  • 2021-01-30 09:59

    As of typescript 2 (or 2.x, not sure), you should import the chrome types from @types.

    in package.json:

    "devDependencies": {
        ...
        "@types/chrome": "0.0.35", // or just npm install --save-dev @types/chrome
    

    And in tsconfig:

        "types": [
            //(various types, e.g. jquery, core-js),
            "chrome"
        ]
    
    0 讨论(0)
提交回复
热议问题