问题
I'm trying out the Angular to develop google extension, but found that I can't reference the chrome
object without generating the
ERROR in E:/ChromeExtensions/.../node_modules/chrome-promise/chrome-promise.d.ts (2160,66): Cannot find namespace 'chrome'.
or
ERROR in E:/ChromeExtensions/.../src/app/chrome-tabs.servi ce.ts (14,7): Cannot find name 'chrome'.
I have added chrome typings npm install --save @types/chrome
but all it gave me was, just typings, but it doesnt resolves build errors.
If that matters:
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
@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
Any suggestions?
回答1:
Based on How to use chrome-app.d.ts type in angular-cli 1.0.1 app?
- I added
@types/chrome
to package.json - I added
/// <reference types="chrome"/>
to the top of my ts file
回答2:
Update for 2019:
There's no need to use /// <reference types="chrome"/>
anymore. npm i @types/chrome
should be enough.
This sometimes happens when you clone a repo that already has a @types
library installed. npm i
doesn't get it done, but if you install the @types
library again, it should work.
回答3:
It would nice to have a code snippet for context.
However, when I ran into this, it was because I was passing chrome
into my function as an argument. It's silly to do that, however, since chrome
is a global variable, and thus accessible from any file. Not only that, but since JavaScript objects are pass-by-reference, there's no need to pass around globals (you're editing the same object regardless).
TL;DR: Add types/chrome
to package.json
, and just access globals (i.e., chrome
or window
) from the file you're working in rather than passing it as an argument.
Passing chrome
as argument (bad / unnecessary):
export function getItem(key: string, chromeStore: chrome): string {
chromeStore.storage.local.get(key, (items: any) => {
...
});
}
Using chrome
as global (good):
export function getItem(key: string): string {
chrome.storage.local.get(key, (items: any) => {
...
});
}
来源:https://stackoverflow.com/questions/47075437/cannot-find-namespace-name-chrome