如何在package.json文件中构建服务工作者?

时间:2019-11-28 16:37:57

标签: reactjs service-worker

这是我package.json文件的顶部:

{
"name": "genta",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"serve": "http-server ./build -c-1",
"watch": "watchify -e  ./src/index.js -o ./build/assets/js/client.bundle.js -t [ babelify ] -t [ envlocalify ]",
"build": "npm run compile && npm run minify",
"compile": "browserify -e  ./src/index.js -o ./build/assets/js/client.bundle.js -t [ babelify ] -t [ envlocalify --envfile .env.prod ]",
"minify": "uglifyjs  ./build/assets/js/client.bundle.js -o ./build/assets/js/client.bundle.js -c -m",
"start": "npm-run-all --parallel watch serve",
"sync": "npm run build && aws s3 sync build/ s3://spark.generaltraffic.co.uk --profile=genta-s3 --acl public-read --exclude 'node_modules/*|.env'"
},

这是我的serviceWorker.js文件:

self.addEventListener('install', (e) => {
    console.log('Service Worker Installed');
});

这是我的index.js文件(主要位于package.json中):

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
    <App />,
    document.getElementById('app')
);

if ('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
            console.log('window loaded')
            navigator.serviceWorker
            .register('../serviceWorker.js')
            .then(reg => {
                console.log('Service worker registered value', reg);
            })
            .catch(err => {
                console.log(`Service worker Error: ${err}`);
            })
        })
    };

我目前在浏览器中收到此错误:

服务人员错误:类型错误:无法使用脚本('https://spark.generaltraffic.co.uk/')为范围('https://spark.generaltraffic.co.uk/serviceWorker.js')注册范围('https://developer.android.com/google/play/billing/billing_rewarded_products')的ServiceWorker:获取错误的HTTP响应代码(403)脚本。

1 个答案:

答案 0 :(得分:0)

您问题的标题实际上与您遇到的错误并不完全对应:-)

控制台中的错误消息内容如下: 浏览器尝试通过URL“ https://spark.generaltraffic.co.uk/serviceWorker.js”注册服务工作者,但服务器以HTTP 403 Forbidden(HTTP 403禁止)响应-这导致注册服务工作者失败。

如果您转到该地址-https://spark.generaltraffic.co.uk/serviceWorker.js-您将看到服务器未在提供您的SW文件,而是提供了HTTP403。您必须先对其进行修复。因此,请通过在浏览器中检查SW脚本来确保该SW脚本可用,然后再尝试查看该页面是否注册了SW等等。