不能使用" import / require"进入服务工作者文件

时间:2018-02-14 10:12:42

标签: reactjs

我目前正在建立一个pwa app with react。我现在正面临着一个问题。确实,我试图导入我的sw.js,它位于公共文件夹中,来自我的src文件夹中的一些函数......但每次我尝试运行应用程序时,我都收到以下消息:

  

"未捕获的SyntaxError:意外的令牌*" "未捕获的SyntaxError:   意外的令牌{" " ..."

这很奇怪,因为它是一个基本的JS文件...

这是我的项目结构:

- node_modules
- public
  - assets
    - images
      (...)
  - favicon.icon
  - index.html
  - manifest.json
  - sw.js
- src
  (...)
  - indexedDB
    - database.js
    - idb.js

(...)

这是我的database.js

import * as idb from './idb.js';


(function() {

emergencyDb = () => {
    return idb.open('emergency-store', 2, upgradeDB => {
        switch (upgradeDB.oldVersion) {
            case 0: upgradeDB.createObjectStore('emergency', { autoIncrement : true })
        }
    })
};

putEmergency = (value, key) => {
    console.log('val dans putEmergency', value);
    console.log('key dans putEmergency', key);
    return databaseLocale().emergencyDb().then(db => {
        const tx = db.transaction('emergency', 'readwrite');
        tx.objectStore('emergency').put(value, key);
        return tx.complete;
    });
};

getEmergency = (id) => {
    return databaseLocale().emergencyDb().then(db => {
        return db.transaction('emergency')
            .objectStore('emergency').get(id);
    })
};

deleteEmergency = (id) => {
    return databaseLocale().emergencyDb().then(db => {
        const tx = db.transaction('emergency', 'readwrite');
        tx.objectStore('emergency').delete(id);
        return tx.complete;
    });
};

clearEmergency = () => {
    return databaseLocale().emergencyDb().then(db => {
        const tx = db.transaction('emergency', 'readwrite');
        tx.objectStore('emergency').clear();
        return tx.complete;
    });
};

getAllEmergency = () => {
    return databaseLocale().emergencyDb().then(db => {
        return db.transaction('emergency')
            .objectStore('emergency').getAllKeys().then(keys => {
                return Promise.all(keys.map(id => databaseLocale().getEmergency(id).then(content => (Object.assign({}, { id }, content)))))
            });
    })
}


}());

我的idb.js

  (function() {

    function toArray(arr) {
      return Array.prototype.slice.call(arr);
    }

    function promisifyRequest(request) {
      return new Promise(function(resolve, reject) {
        request.onsuccess = function() {
          resolve(request.result);
        };

        request.onerror = function() {
          reject(request.error);
        };
      });
    }

    function promisifyRequestCall(obj, method, args) {
      var request;
      var p = new Promise(function(resolve, reject) {
        console.log('obj', JSON.stringify(obj));
        console.log('method', method);
        console.log('args', args);
        request = obj[method].apply(obj, args);
        promisifyRequest(request).then(resolve, reject);
      });

      p.request = request;
      return p;
    }

    function promisifyCursorRequestCall(obj, method, args) {
      var p = promisifyRequestCall(obj, method, args);
      return p.then(function(value) {
        if (!value) return;
        return new Cursor(value, p.request);
      });
    }

    function proxyProperties(ProxyClass, targetProp, properties) {
      properties.forEach(function(prop) {
        Object.defineProperty(ProxyClass.prototype, prop, {
          get: function() {
            return this[targetProp][prop];
          },
          set: function(val) {
            this[targetProp][prop] = val;
          }
        });
      });
    }

    function proxyRequestMethods(ProxyClass, targetProp, Constructor, properties) {
      properties.forEach(function(prop) {
        if (!(prop in Constructor.prototype)) return;
        ProxyClass.prototype[prop] = function() {
          console.log('this', this);
          console.log('targetProp', targetProp);
          console.log('prop', prop);
          console.log('arguments', arguments);
          return promisifyRequestCall(this[targetProp], prop, arguments);
        };
      });
    }

    function proxyMethods(ProxyClass, targetProp, Constructor, properties) {
      properties.forEach(function(prop) {
        if (!(prop in Constructor.prototype)) return;
        ProxyClass.prototype[prop] = function() {
          return this[targetProp][prop].apply(this[targetProp], arguments);
        };
      });
    }

    function proxyCursorRequestMethods(ProxyClass, targetProp, Constructor, properties) {
      properties.forEach(function(prop) {
        if (!(prop in Constructor.prototype)) return;
        ProxyClass.prototype[prop] = function() {
          return promisifyCursorRequestCall(this[targetProp], prop, arguments);
        };
      });
    }

    function Index(index) {
      this._index = index;
    }

    proxyProperties(Index, '_index', [
      'name',
      'keyPath',
      'multiEntry',
      'unique'
    ]);

    proxyRequestMethods(Index, '_index', IDBIndex, [
      'get',
      'getKey',
      'getAll',
      'getAllKeys',
      'count'
    ]);

    proxyCursorRequestMethods(Index, '_index', IDBIndex, [
      'openCursor',
      'openKeyCursor'
    ]);

    function Cursor(cursor, request) {
      this._cursor = cursor;
      this._request = request;
    }

    proxyProperties(Cursor, '_cursor', [
      'direction',
      'key',
      'primaryKey',
      'value'
    ]);

    proxyRequestMethods(Cursor, '_cursor', IDBCursor, [
      'update',
      'delete'
    ]);

    // proxy 'next' methods
    ['advance', 'continue', 'continuePrimaryKey'].forEach(function(methodName) {
      if (!(methodName in IDBCursor.prototype)) return;
      Cursor.prototype[methodName] = function() {
        var cursor = this;
        var args = arguments;
        return Promise.resolve().then(function() {
          cursor._cursor[methodName].apply(cursor._cursor, args);
          return promisifyRequest(cursor._request).then(function(value) {
            if (!value) return;
            return new Cursor(value, cursor._request);
          });
        });
      };
    });

    function ObjectStore(store) {
      this._store = store;
    }

    ObjectStore.prototype.createIndex = function() {
      return new Index(this._store.createIndex.apply(this._store, arguments));
    };

    ObjectStore.prototype.index = function() {
      return new Index(this._store.index.apply(this._store, arguments));
    };

    proxyProperties(ObjectStore, '_store', [
      'name',
      'keyPath',
      'indexNames',
      'autoIncrement'
    ]);

    proxyRequestMethods(ObjectStore, '_store', IDBObjectStore, [
      'put',
      'add',
      'delete',
      'clear',
      'get',
      'getAll',
      'getKey',
      'getAllKeys',
      'count'
    ]);

    proxyCursorRequestMethods(ObjectStore, '_store', IDBObjectStore, [
      'openCursor',
      'openKeyCursor'
    ]);

    proxyMethods(ObjectStore, '_store', IDBObjectStore, [
      'deleteIndex'
    ]);

    function Transaction(idbTransaction) {
      this._tx = idbTransaction;
      this.complete = new Promise(function(resolve, reject) {
        idbTransaction.oncomplete = function() {
          resolve();
        };
        idbTransaction.onerror = function() {
          reject(idbTransaction.error);
        };
        idbTransaction.onabort = function() {
          reject(idbTransaction.error);
        };
      });
    }

    Transaction.prototype.objectStore = function() {
      return new ObjectStore(this._tx.objectStore.apply(this._tx, arguments));
    };

    proxyProperties(Transaction, '_tx', [
      'objectStoreNames',
      'mode'
    ]);

    proxyMethods(Transaction, '_tx', IDBTransaction, [
      'abort'
    ]);

    function UpgradeDB(db, oldVersion, transaction) {
      this._db = db;
      this.oldVersion = oldVersion;
      this.transaction = new Transaction(transaction);
    }

    UpgradeDB.prototype.createObjectStore = function() {
      return new ObjectStore(this._db.createObjectStore.apply(this._db, arguments));
    };

    proxyProperties(UpgradeDB, '_db', [
      'name',
      'version',
      'objectStoreNames'
    ]);

    proxyMethods(UpgradeDB, '_db', IDBDatabase, [
      'deleteObjectStore',
      'close'
    ]);

    function DB(db) {
      this._db = db;
    }

    DB.prototype.transaction = function() {
      return new Transaction(this._db.transaction.apply(this._db, arguments));
    };

    proxyProperties(DB, '_db', [
      'name',
      'version',
      'objectStoreNames'
    ]);

    proxyMethods(DB, '_db', IDBDatabase, [
      'close'
    ]);

    // Add cursor iterators
    // TODO: remove this once browsers do the right thing with promises
    ['openCursor', 'openKeyCursor'].forEach(function(funcName) {
      [ObjectStore, Index].forEach(function(Constructor) {
        Constructor.prototype[funcName.replace('open', 'iterate')] = function() {
          var args = toArray(arguments);
          var callback = args[args.length - 1];
          var nativeObject = this._store || this._index;
          var request = nativeObject[funcName].apply(nativeObject, args.slice(0, -1));
          request.onsuccess = function() {
            callback(request.result);
          };
        };
      });
    });

    // polyfill getAll
    [Index, ObjectStore].forEach(function(Constructor) {
      if (Constructor.prototype.getAll) return;
      Constructor.prototype.getAll = function(query, count) {
        var instance = this;
        var items = [];

        return new Promise(function(resolve) {
          instance.iterateCursor(query, function(cursor) {
            if (!cursor) {
              resolve(items);
              return;
            }
            items.push(cursor.value);

            // Modification ici 
            // if (count !== undefined && items.length == count) {
            if (count !== undefined && items.length === count) {
              resolve(items);
              return;
            }
            cursor.continue();
          });
        });
      };
    });

    var exp = {
      open: function(name, version, upgradeCallback) {
        var p = promisifyRequestCall(indexedDB, 'open', [name, version]);
        var request = p.request;

        request.onupgradeneeded = function(event) {
          if (upgradeCallback) {
            upgradeCallback(new UpgradeDB(request.result, event.oldVersion, request.transaction));
          }
        };

        return p.then(function(db) {
          return new DB(db);
        });
      },
      delete: function(name) {
        return promisifyRequestCall(indexedDB, 'deleteDatabase', [name]);
      }
    };

    if (typeof module !== 'undefined') {
      module.exports = exp;
      module.exports.default = module.exports;
    }
    else {
      this.idb = exp;
    }
  }());

最后是我的sw.js

// import * as idb from './assets/indexedDB/idb.js'; < -- BUG HERE CANNOT IMPORT THE FILE


const BASE_URL_BACKEND = 'http://localhost:8080';

const cacheName ='emmergency-1.0';

self.addEventListener('install', evt => {
    console.log(`SW installé à ${new Date().toLocaleTimeString()}`);

    let cachePromise = caches.open(cacheName).then(cache =>{
        return cache.addAll([
            '/'
        ])
        .then(console.log("Cache initialisé"))
        .catch(console.err);
    });

    evt.waitUntil(cachePromise);
});


// Supprimer les anciennes versions du cache
self.addEventListener('activate', evt => {
    console.log('Activate evt', evt);
    let cacheCleanedPromise = caches.keys().then(keys => {
        keys.forEach(key => {
            if(key != cacheName){
                return caches.delete(key);
            }
        })
    });
    evt.waitUntil(cacheCleanedPromise)
});



self.addEventListener('fetch', evt => {
    // if(!navigator.onLine){
    //     const headers = { headers : {'Content-Type': 'text/html;charset=utf-8'}};
    //     evt.respondWith(new Response('<h1>Pas de connexion internet</h1>', headers));
    // }


    // // Stratégie de cache only with network fallback
    // evt.respondWith(
    //     caches.match(evt.request).then(res => {
    //         if(res){
    //             console.log(`Url fetchée depuis le cache ${evt.request.url}`, res);
    //             return res;
    //         }
    //         return fetch(evt.request).then(newResponse => {
    //             console.log(`Url récrupérée sur le réseau puis mise en cache ${evt.request.url}`, newResponse);

    //             caches.open(cacheName).then(cache => cache.put(evt.request, newResponse))
    //             return newResponse.clone();
    //         })
    //     })
    // );

    // Stratégie de network first with cache fallback
    // evt.respondWith(
    //     fetch(evt.request).then(res => {
    //         console.log(`${evt.request.url} fetchée depuis le réseau`);
    //         caches.open(cacheName).then(cache => cache.put(evt.request, res));
    //         return res.clone();
    //     }).catch(err => {
    //         console.log(`${evt.request.url} fetchée depuis le cache`);
    //         return caches.match(evt.request);
    //     })
    // );

});


// // Notification persistante - Peut être affiché même quand l'utilisateur n'est pas sur l'application
// self.registration.showNotification("Notification depuis le SW", {
//     body : 'Je suis un notification "persistante"',
//     actions : [
//         {action : 'accept', title: 'Accepter'},
//         {action : 'refuse', title: 'Refuser'}
//     ]
// })

// self.addEventListener('notificationclose', evt => {
//     console.log('Notification fermée', evt); 
// })

// self.addEventListener('notificationclick', evt => {
//     if(evt.action === 'accept'){
//         console.log('Notification acceptée');
//     }
//     else if(evt.action === 'refuse'){
//         console.log('Notification refusée');
//     }
//     else{
//         console.log('Vous avez cliqué sur la notification (Pas sur les boutons)');
//     }

//     evt.notification.close();
// })


self.addEventListener('push', evt => {
    console.log('Push event', evt);
    console.log('Data envoyée par la push notification des dev tools : ', evt.data.text());
    const title = evt.data.text();

    evt.waitUntil(
        self.registration.showNotification(title, 
            { 
                body: 'Ca fonctionne', 
                image: 'images/icons/icon-152x152.png'
            }
        ));
})

self.addEventListener('sync', event => {
    if(event.tag === 'sync-emergencies'){
        console.log('Attemting to sync', event.tag);

        event.waitUntil(
            getAllEmergency().then(emergencies => {
                const unsynced = emergencies.filter(emergency => emergency.unsynced);

                console.log("UNSYNCED =", unsynced);

                return Promise.all(unsynced.map(emergency => {
                    fetch(`${BASE_URL_BACKEND}/api/calls`, {
                        headers : {
                            'Accept': 'application/json',
                            'Content-Type' : 'application/json'
                        },
                        method: 'POST',
                        body: JSON.stringify(emergency)
                    })
                    .then(() => {
                        return putEmergency(Object.assign({}, emergency, { unsynced: false}), emergency.id);
                    });
                }))
            })
        )
    }
});

我绝对需要来自&#34; database.js&#34;的一些功能。进入我的&#34; sw.js&#34;文件...但我无法导入...请帮忙吗?

谢谢

1 个答案:

答案 0 :(得分:0)

IIFE没有回复。您需要添加它。

<强> idb.js

(function() {
      //......

        return {
            exp
        }

  }());