Caching ServiceWorkers和Next.js:如何将生产中的服务人员与Next.js应用程序集成?

Caching ServiceWorkers和Next.js:如何将生产中的服务人员与Next.js应用程序集成?,caching,next.js,service-worker,Caching,Next.js,Service Worker,我正在使用“next”:“^9.3.2”,并集成了一名服务人员(包括此项,以防其他人有类似问题): 文件结构: pages public static serviceWorker.js server index.js 在server/index.js中 async function start() { const dev = process.env.NODE_ENV !== 'production'; const app = nextJS({ dev }); c

我正在使用
“next”:“^9.3.2”
,并集成了一名服务人员(包括此项,以防其他人有类似问题):

文件结构:

pages
public
  static
  serviceWorker.js
server
  index.js
server/index.js中

 async function start() {
   const dev = process.env.NODE_ENV !== 'production';
   const app = nextJS({ dev });
   const server = express();
   
   ....
    server.get('/serviceWorker.js', (req, res) => {
      res.sendFile(path.resolve(__dirname, '../public', 'serviceWorker.js'));
   });

   /* later */

    if (process.env.NODE_ENV === 'production') {
       server.use(express.static('.next/static'));
       server.get('/service-worker.js', (req, res) => {
       res.sendFile(path.resolve(__dirname, 'public', 'serviceWorker.js'));
    });
public/serviceWorker.js中

 async function start() {
   const dev = process.env.NODE_ENV !== 'production';
   const app = nextJS({ dev });
   const server = express();
   
   ....
    server.get('/serviceWorker.js', (req, res) => {
      res.sendFile(path.resolve(__dirname, '../public', 'serviceWorker.js'));
   });

   /* later */

    if (process.env.NODE_ENV === 'production') {
       server.use(express.static('.next/static'));
       server.get('/service-worker.js', (req, res) => {
       res.sendFile(path.resolve(__dirname, 'public', 'serviceWorker.js'));
    });
var currentCaches={ css:'css', 图像:“图像” };

const缓存文件={
css:[
// 'http://localhost:8016/semantic-ui css/semantic.min.css',
// 'http://localhost:8016/font-awesome/css/font awesome.min.css',
// 'http://localhost:8016/leaflet/dist/leaflet.css',
// 'http://localhost:8016/esri-传单地理编码器/dist/esri传单地理编码器.css',
// 'http://localhost:8016/styles/styles.css',
// 'http://localhost:8016/leaflet-路由机器/dist/传单路由机器.css'
],
图像:[
// 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png',
// 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png',
// 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
// 'http://localhost:8016/public/static/media/search@2x.png',
// 'http://localhost:8016/public/static/uploads/profile-头像/占位符.jpg'
]
};
self.addEventListener('install',函数(事件){

console.log('Hello world from the Service Worker一般来说,如果您想获得在服务人员中使用的哈希URL列表,您需要某种方式与web应用程序的构建过程集成

考虑到您正在使用Next.js,像这样的插件可以通过做两件事来帮助您:

  • 与构建过程集成以获得哈希URL列表
  • 为您生成整个服务人员,使用UndertheHood确保正确缓存URL并保持最新

如果您不想在下一次脱机时使用
,您可以自己实现类似的功能,但您需要使用类似的功能来获取哈希URL列表,编写您自己的服务工作者,并找出如何将这些URL注入服务工作者中。

非常感谢Jeff!我将对此进行研究。首先,请考虑是否对js以及他们所能做的,我想从没有抽象开始,但考虑到你所说的,我可能会试着关注抽象,这样就不会觉得那么神奇了!