Javascript 找不到服务工作程序终结点
我刚刚为我的项目设置了服务人员。我的Javascript 找不到服务工作程序终结点,javascript,webpack,service-worker,workbox-webpack-plugin,Javascript,Webpack,Service Worker,Workbox Webpack Plugin,我刚刚为我的项目设置了服务人员。我的webpack.config.js如下所示 const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const WorkboxPlugin =
webpack.config.js
如下所示
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const WorkboxPlugin = require('workbox-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js',
worker: './src/worker.js',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
plugins: [
new CleanWebpackPlugin(),
new webpack.ProgressPlugin(),
new HtmlWebpackPlugin({
title: 'PWA'
}),
new WorkboxPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: true,
}),
new webpack.HotModuleReplacementPlugin()
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
devServer: {
contentBase: './dist',
hot: true
}
};
我的package.json
也被设置为
"scripts": {
"start": "webpack-dev-server --config ./webpack.config.js --mode development",
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
通过将以下代码添加到我的index.js
文件中,我可以成功注册工人
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js').then(registration => {
console.log('SW registered: ', registration);
}).catch(registrationError => {
console.log('SW registration failed: ', registrationError);
});
});
}
但是,现在我不知道在哪里定义端点。我想在我的应用程序中的某个地方定义以下代码,但我不知道如何确保端点被调用
self.addEventListener('fetch', function(event) {
console.log("Caught a fetch!");
event.respondWith(new Response("Hello world!"));
});
如果我运行
npm build
,将在我的dist
文件夹中生成sw.js
文件,因此我尝试在那里添加端点。但是,当我在之后运行npmstart
时,该端点永远不会被调用,文件也会消失(我猜它被捆绑在某个地方)。有人能解释一下我做错了什么吗?我需要在哪里定义我的端点以及如何调用它们?我可以通过将webpack.config.js
更改为使用InjectManifest
使其正常工作
new WorkboxPlugin.InjectManifest({
swSrc: "./src/src-sw.js",
swDest: "sw.js"
})
因此,现在在src sw.js
中,我添加了以下内容
self.addEventListener("install", event => {
console.log("Installed");
});
我可以在控制台中获取日志