找不到命名空间/名称chrome

时间:2017-11-02 12:34:28

标签: javascript angular google-chrome-extension

我尝试使用Angular来开发Google扩展程序,但发现我无法在不生成

的情况下引用chrome对象
  

E:/ ChromeExtensions /.../ node_modules / chrome-promise / chrome-promise.d.ts(2160,66)中的错误:无法找到命名空间' chrome'。

  

E:/ ChromeExtensions /.../ src / app / chrome-tabs.servi中的错误   ce.ts(14,7):找不到名字' chrome'。

我添加了chrome typings npm install --save @types/chrome,但它给了我的只是打字,但它并没有解决构建错误。

如果重要:

    _                      _                 ____ _     ___
   / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
  / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
 / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
/_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
               |___/
@angular/cli: 1.4.9
node: 6.11.4
os: win32 x64
@angular/animations: 4.4.6
@angular/common: 4.4.6
@angular/compiler: 4.4.6
@angular/core: 4.4.6
@angular/forms: 4.4.6
@angular/http: 4.4.6
@angular/platform-browser: 4.4.6
@angular/platform-browser-dynamic: 4.4.6
@angular/router: 4.4.6
@angular/cli: 1.4.9
@angular/compiler-cli: 4.4.6
@angular/language-service: 4.4.6
typescript: 2.3.4

Visual Studio Code 1.17.2

有什么建议吗?

3 个答案:

答案 0 :(得分:2)

2019年更新

不再需要使用<div className={classes.modalContainer}>/// <reference types="chrome"/>应该足够。

当您克隆已经安装了npm i @types/chrome库的存储库时,有时会发生这种情况。 @types并没有完成,但是如果您再次安装npm i库,它应该可以工作。

答案 1 :(得分:1)

基于How to use chrome-app.d.ts type in angular-cli 1.0.1 app?

  1. 我在package.json中添加了@types/chrome
  2. 我在ts文件顶部添加了/// <reference types="chrome"/>

答案 2 :(得分:1)

最好有一个上下文代码段。

但是,当我遇到这个问题时,是因为我将chrome作为参数传递给了我的函数。但是,这样做很愚蠢,因为chrome是全局变量,因此可以从任何文件访问。不仅如此,而且由于JavaScript对象是按引用传递的,因此无需传递全局变量(无论如何,您都在编辑同一对象)。

TL; DR:将types/chrome添加到package.json,并且仅从正在处理的文件中访问全局变量(即chromewindow),而不是传递作为参数。

chrome作为参数传递(错误/不必要):

export function getItem(key: string, chromeStore: chrome): string {
  chromeStore.storage.local.get(key, (items: any) => {
    ...
  });
}

chrome用作全局(良好):

export function getItem(key: string): string {
  chrome.storage.local.get(key, (items: any) => {
    ...
  });
}
相关问题