angular2 / typescript项目中的未定义变量localforage

时间:2016-04-03 08:02:46

标签: typescript angular localforage

我在将localForage添加到angular2-seed项目时遇到问题(使用typings和webpack)。我是打字和angular2的新手。

使用typings命令,我将Typescript定义添加到typings.json

    "localforage": "registry:dt/localforage#0.0.0+20160316155526",

在我的vendor.ts文件中,我添加了

const localforage:LocalForage = require("localforage");

在我的service.ts文件中,我的IDE可以解析导入并自动完成

import {localforage} from "localforage";

this.store = localforage.createInstance({
  name: "products"
})

但是当我运行应用程序时,导入的localforage是undefined

ORIGINAL EXCEPTION: TypeError: Cannot read property 'createInstance' of undefined
ORIGINAL STACKTRACE:
TypeError: Cannot read property 'createInstance' of undefined
    at new SearchService (eval at <anonymous> (http://localhost:3000/app.bundle.js:36:2), <anonymous>:20:53)
    at eval (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:189:2), <anonymous>:13:47)
    at Injector._instantiate (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:777:27)
    at Injector._instantiateProvider (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:715:25)
    at Injector._new (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:704:21)
    at InjectorInlineStrategy.getObjByKeyId (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:247:33)
    at Injector._getByKeyDefault (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:921:37)
    at Injector._getByKey (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:867:25)
    at Injector._getByDependency (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:853:25)
    at Injector._instantiate (eval at <anonymous> (http://localhost:3000/vendor.bundle.js:141:2), <anonymous>:743:36)

有什么建议吗?谢谢!

3 个答案:

答案 0 :(得分:2)

看起来您忘记指示systemjs(因为您正在使用angular2我认为它是您的加载器)什么是localforage以及从何处加载它。这样的事情可以解决问题:

System.config({
 .....
  paths: {
    localforage: 'path/to/localforage/dist/localforage'
  }
 .....
});

System.defaultJSExtensions = true;

希望这有帮助

答案 1 :(得分:0)

键入仅用于编译而不用于运行时。因此,您需要在条目HTML文件中配置SystemJS:

System.config({
  map: {
    localforage: '/path/to/localforage.js'
  },
  (...)
});

这样您就可以导入localforage模块:

import localforage from 'localforage';

答案 2 :(得分:0)

最后,这不是脚本加载问题,但我忘了在export

中添加vendor.ts关键字
export const localforage:LocalForage = require("localforage");