【问题标题】:Adding service workers in Aurelia在 Aurelia 中添加服务人员
【发布时间】:2019-04-04 11:36:35
【问题描述】:

为了使我的 aurelia 应用程序成为我使用 aurelia cli 创建的正确 PWA,我需要注册一个 service worker。

网上已经有类似的未答复的question 或很少的discussionsforum posts 可用,但我找不到任何具体的信息来帮助我开始。

我正在考虑三种可能的方法来处理这个问题

选项[1] - 使用 index.html 页面并在 aurelia 应用范围之外的脚本标签内注册服务佩戴者。

// service worker in index.html file

<!DOCTYPE html>
<html>
  <head>

  </head>
  <body aurelia-app="main">

  <script type="text/javascript"> 
     ... my service worker code here ...
  </script>
  </body>
</html>

选项[2] - 在 aurelia main.js/main.ts 中

// inside aurelia main.js/main.ts file

export function configure(aurelia) {
  ... rest of the conf ...
  registerServiceWorker();
  return aurelia.start().then(() => aurelia.setRoot(PLATFORM.moduleName('app')));
}

选项 [3] - app.js 文件

// inside app.js file constructor

export class App {

  constructor() {

    this.registerServiceWorker();
  }

处理此任务的正确/正确方法是什么?当我使用 webpack 时,是否需要更多配置才能使 service worker 与 webpack 和 aurelia 配合得很好?

如果使用 WorkBox 是唯一的出路,我也可以接受,但为了简单起见,我更喜欢直接在 aurelia 中使用 vanilla service workers。

【问题讨论】:

    标签: javascript service-worker aurelia


    【解决方案1】:

    这就是我让它工作的方式。

    1- insatll 工作箱插件

    yarn add workbox-webpack-plugin
    

    2- 配置 webpack

    //webpack.config.js
    // add plugin somewhere in the top section 
    
    const  workboxPlugin = require('workbox-webpack-plugin');
    
    //inside plugins section 
     plugins: [
       // somewhere in the bottom is OK 
       new workboxPlugin.GenerateSW({
          swDest: 'sw.js', // name of your service worker file
          clientsClaim: true,
          skipWaiting: true
        }),
    

    3- 将您的 sw.js 文件放在静态目录中。它将在构建时移动到 dist 文件夹。

    4- 如果是完整的 PWA,请在静态目录中添加 manifest.json 文件。您可以从 google developr site 获取示例 manifest.json 文件。

    5- 将 service worker 初始化脚本添加到索引文件中

     // index.html or index.ejs file
     <script>
    
      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('/sw.js')
          .then(function(registration) { return registration.update(); })
          .catch(error => console.log(error));
      }
    
    </script>
    

    运行,希望您应该安装并运行 serviceiceworker。

    附:这是正确的方法吗?我不知道,但现在它对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多