如何摆脱打字稿错误信息 "Cannot find module 'localforage'"

how to get rid of typescript error message "Cannot find module 'localforage'"

我正在做一个 ionic 2/cordova 项目,并且正在使用 vim 和 typescript 支持。

我的代码中有以下行:

import * as localforage from "localforage";

代码 运行 没有问题,但打字稿编译器给出以下错误

/path/to/file.ts|2 col 30 error| Cannot find module 'localforage'.

任何提示如何避免该错误?

更新

import {Injectable} from "angular2/core";
import * as localforage from "localforage";

@Injectable()
export class DbService {

  constructor() {
    //this.run();
  }

  setKeyVal(k, v){
    console.log("db service setKeyVal");
    let ran = Math.floor(Math.random() * 1000) + 1;
    localforage.setItem(k, device.uuid).then(function () {
      return localforage.getItem(k);
    }).then(function (value) {
      console.log(value);
      // we got our value
      console.log(navigator.connection.type);
      console.log("setItem then");
    }).catch(function (err) {
      // we got an error
      console.log("setItem catch");
    });
  }
}

更新 1 - typings.json

{
  "dependencies": {},
  "devDependencies": {},
  "ambientDependencies": {
    "cordova-ionic": "registry:dt/cordova-ionic#0.0.0+20160316155526",
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-shim.d.ts#4de74cb527395c13ba20b438c3a7a419ad931f1c",
    "localforage": "registry:dt/localforage#0.0.0+20160316155526"
  }
}

更新 2 - tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "filesGlob": [
    "**/*.ts",
    "!node_modules/**/*"
  ],
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}

首先 - 从以下位置安装类型定义:localforage

其次 - 将导入更改为:

import {localforage} from 'localforage';

我已经尝试为 localforage 安装 typeings,但它对我不起作用。

typings install localforage --ambient --save

但我可以用 tds 做到这一点。

npm i tsd -g
tsd install localforage

我使用的是 Ionic2 Beta.29 版本

更新/typeings/index.d.ts

/// <reference path="localForage/localForage.d.ts" />

添加这一行。

最后,导入为

import {localforage} from 'localforage';

就是这样,现在一切正常。

我已经尝试了 typings installtsd install 命令。但其中 none 有效。最后我从离子论坛找到了解决方案:here.

希望这对遇到同样问题的人有所帮助。

第 1 步:安装 Mozilla localForage。

$ npm install localforage --save

第 2 步:安装 localForage 类型定义。

$ npm install -g typings
$ typings install dt~localforage --save --global

我没有将导入更改为 import {localforage} from 'localforage';。将其保留为

import LocalForage from 'localforage';

我遇到运行时错误找不到模块“localforage”。我运行命令

npm uninstall --save @ionic/storage
npm install --save @ionic/storage

对我有帮助