4

I'm writing PWA app. I was using default Service Worker from template that I'm using (Vue.js PWA template), but now I have decided to write my own from the scratch. I have placed it (service-worker.js) into static folder, because I want to have static name for it - I don't want to change name each time (build).

In this particular Service Worker I want to use package name and version, so that I can nicely generate cache ID.

So I want to achieve something like this:

./package.json:

{ "name": "my.app", "version": "1.0.0", ... }

./static/service-worker.js: var CACHE_ID = 'PACKAGE_NAME-vPACKAGE_VERSION'; ...

./build/service-worker.js: var CACHE_ID = 'my.app-v1.0.0';

The ./build/service-worker.js shows what I want to achieve.

I have tried https://www.npmjs.com/package/string-replace-loader with below configuration:

  {
    test: /service-worker\.js$/,
    loader: 'string-replace-loader',
    options: {
      multiple: [
        {
          search: 'PACKAGE_NAME',
          replace: packageConfig.name
        },
        {
          search: 'PACKAGE_VERSION',
          replace: packageConfig.version
        }
      ]
    }
  }

But as I understand files placed in static are not modules (am I right?), so those are not checked by module.rules.

I would be greatful for help and/or guidence how I can solve this problem.

4

2 回答 2

3

好的,我终于明白了。我已经使用copy-webkit-plugin并且可以转换:

  plugins: [
    new CopyWebpackPlugin([
      {
        from: 'static/service-worker.js',
        to: './service-worker.js',
        transform (content) {
          var parsed = content.toString();
          var transformation = [
            {
              search: 'PACKAGE_NAME',
              replace: packageConfig.name
            },
            {
              search: 'PACKAGE_VERSION',
              replace: packageConfig.version
            }
          ];

          for(var i = 0; i < transformation.length; i++) {
            parsed = parsed.replace(transformation[i].search, transformation[i].replace);
          }

          return Buffer.from(parsed, 'utf8');
        }
      }
    ])
  ]
于 2018-06-27T12:59:44.877 回答
2

模块

模块放置在node_modules. src是您的源文件夹,您应该只保留您不会在production模式下使用的文件。

还要记住,模块只不过是类似于库的 JavaScript 代码;一组功能。如果您将 *.js 文件从移动node_modulessrc- 这仍然是模块。

我真的不明白您为什么要使用string-replace-loader它,因为它与您的问题无关。

Loader 允许以 String.prototype.replace() 的方式执行替换(loader 在内部使用它)。这意味着如果你想替换所有出现的地方,你应该在 options.search 中使用类似 RegExp 的字符串,在 options.flags 等中使用 g 标志。

MDNString.prototype.replace()中:

replace() 方法返回一个新字符串,其中模式的部分或全部匹配被替换替换。模式可以是字符串或正则表达式,替换可以是字符串或每次匹配调用的函数。

还是我误会了你?

工人装载机

但如果我理解正确的话——实际上有一个工人装载机。

$ npm install worker-loader --save-dev
于 2018-06-27T08:33:53.780 回答