Я пытаюсь настроить проект в React с рендерингом на стороне сервера и PWA. У меня есть настройка React с рендерингом на стороне сервера, но когда я пытаюсь добавить PWA, я не могу сделать.
Это структура моего проекта. ![enter image description here](https://i.stack.imgur.com/k9Lme.png)
webpack.config. js
const path = require('path');
module.exports = {
mode: 'development',
entry: {
client: './src/client.js',
bundle: './src/bundle.js'
},
output: {
path: path.resolve(__dirname, 'assets'),
filename: "[name].js"
},
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
]
}
}
пакет. json
{
"name": "react-poc",
"version": "1.1.0",
"description": "react-poc",
"main": "index.js",
"scripts": {
"start": "yarn build && node index.js",
"build": "webpack --config webpack.config.js"
},
"author": "Piyush Jain",
"license": "MIT",
"dependencies": {
"@babel/register": "^7.8.6",
"express": "^4.17.1",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-redux": "^7.2.0",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"@babel/cli": "^7.8.4",
"@babel/core": "^7.8.7",
"@babel/preset-env": "^7.8.7",
"@babel/preset-react": "^7.8.3",
"babel-loader": "^8.0.6",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11"
}
В моей памяти c папка, я создал файл работника. js
// Flag for enabling cache in production
var doCache = false;
var CACHE_NAME = 'pwa-app-cache';
// Delete old caches
self.addEventListener('activate', event => {
const currentCachelist = [CACHE_NAME];
event.waitUntil(
caches.keys()
.then(keyList =>
Promise.all(keyList.map(key => {
if (!currentCachelist.includes(key)) {
return caches.delete(key);
}
}))
)
);
});
// This triggers when user starts the app
self.addEventListener('install', function(event) {
if (doCache) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
fetch('manifest.json')
.then(response => {
response.json();
})
.then(assets => {
// We will cache initial page and the main.js
// We could also cache assets like CSS and images
const urlsToCache = [
'/',
assets['bundle.js']
];
cache.addAll(urlsToCache);
})
})
);
}
});
// Here we intercept request and serve up the matching files
self.addEventListener('fetch', function(event) {
if (doCache) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
}
});
затем я добавил это в html
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('worker.js').then(function(registration) {
console.log('Worker registration successful', registration.scope);
}, function(err) {
console.log('Worker registration failed', err);
}).catch(function(err) {
console.log(err);
});
});
} else {
console.log('Service Worker is not supported by browser.');
}
</script>
Но когда я пытаюсь запустить приложение, я получаю сообщение об ошибке ниже .
Ошибка регистрации работника Ошибка типа: Не удалось зарегистрировать ServiceWorker для области ('http://localhost: 3000 / ') со сценарием ('http://localhost: 3000 /worker.js '): при получении сценария получен неверный код ответа HTTP (404).