【问题标题】:localforage with Require.jslocalforage 与 Require.js
【发布时间】:2018-02-24 23:42:08
【问题描述】:

我正在尝试使用 require.js 加载 localforage 库,但无法正常工作。这是我的 require.js 配置:

main.html:

<body>
 <script type="text/javascript" src="/xyz/js/lib/require-2.1.22.js">  </script>
 <script type="text/javascript" src="/xyz/js/main.js?version=1.0.0"></script>
</body>

main.js:

var appVersion = "1.0.0";
requirejs.config({      
    baseUrl: "../js",
    paths: {
        jquery: "lib/jquery-1.12.1",
        jquery_caret:  "lib/jquery.caret-1.5.1",
        lodash: "lib/lodash-4.5.1",
        localforage: "lib/localforage"
    },      
    shim: {
        jquery_caret: ["jquery"]
    },
    urlArgs: "version=" + appVersion
});

var scriptSources = ["jquery", "jquery_caret", "localforage", "lodash"];    
require(scriptSources, function() {
    //all scripts loaded
});

但是当我以后像这样使用 localforage 时

localforage.setDriver(localforage.INDEXEDDB).then(function() {
    console.log("Hi there");
});

它总是未定义的。顺便提一句。 Dexie 我也有同样的问题。 当我从自述文件中添加以下代码时

define(['localforage'], function(localforage) {
  // As a callback:
  localforage.setItem('mykey', 'myvalue', console.log);

  // With a Promise:
  localforage.setItem('mykey', 'myvalue').then(console.log);
});

我收到来自 requirejs.org/docs/errors.html#mismatch 的错误 但是这是什么意思 ?有人可以向我解释一下吗?我真的不明白。

【问题讨论】:

  • 与此同时,在我看来,我必须将上述定义调用从 "define(['localforage'], function(localForage)" 更改为 "define('localforage', [' localforage'], function(localForage) "。现在调用不再是匿名的了。但是'localforage'仍然是未定义的!?
  • 如果其他人有兴趣,即使我没有使用缩小版,我也可以通过使用这里的解决方案来工作:github.com/mozilla/localForage/issues/58

标签: requirejs localforage


【解决方案1】:

您可以试用 repo 的示例,特别是 this one。 更详细地说,完整的 main.js 文件如下所示:

requirejs.config({
    paths: {
        localforage: 'path/to/dist/localforage'
    }
});
define(['localforage'], function(lf) {
    lf.ready().then(function() {
        var key = 'STORE_KEY';
        var value = 'What we save offline';

        lf.setItem(key, value).then(function() {
            console.log('SAVING', value);

            return lf.getItem(key);
        }).then(function(readValue) {
            console.log('READING', readValue);
        });
    });
});

另外,getItems 插件的an example 看起来也与您的相似。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2014-08-12
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    相关资源
    最近更新 更多