1

我在将 localForage 添加到我的 angular2-seed 项目(使用打字和 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)

有什么建议吗,谢谢!

4

3 回答 3

2

看起来您忘记指示 systemjs(因为您使用的是 angular2,我假设它是您的加载器)什么是 localforage 以及从哪里加载它。这样的事情应该可以解决问题:

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

System.defaultJSExtensions = true;

希望这可以帮助

于 2016-04-03T09:22:58.150 回答
0

最后这不是脚本加载问题,但我忘了添加export关键字vendor.ts

export const localforage:LocalForage = require("localforage");
于 2016-04-03T19:48:59.747 回答
0

类型仅用于编译而不用于运行时。所以你需要在你的入口HTML文件中配置SystemJS:

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

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

import localforage from 'localforage';
于 2016-04-03T09:27:30.453 回答