我刚刚为我的项目设置了服务人员。我的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
的文件夹中生成,所以我尝试在那里添加端点。但是当我之后运行时,该端点永远不会被调用并且文件也消失了(我猜它被捆绑在某个地方)。有人可以向我解释我做错了什么吗?我需要在哪里定义我的端点以及如何调用它们?sw.js
dist
npm start