# All files / src/webpack/plugins sw-variables.js

4.35% Statements 1/23
0% Branches 0/15
0% Functions 0/5
4.55% Lines 1/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50

    2xclass SwVariables {
      constructor(options = {}) {
        this.options = options;
      }
      apply(compiler) {

        const { fileName, variables, text } = this.options;

        compiler.hooks.emit.tap("AddVariableToSw",  (compilation) => {
          const chunks = compilation.chunks;

          const publicPath = compilation.options.output.publicPath;
          const offlineAssetsMapping = [];

          // Start out by getting metadata for all the assets associated with a chunk.
          for (const chunk of chunks) {
            if (!chunk.name) continue;
            for (const file of chunk.files) {
              offlineAssetsMapping.push([publicPath, file].join(""));
            }
          }

          if (compilation.assets[fileName]) {
            let src = compilation.assets[fileName].source();

            if (offlineAssetsMapping && offlineAssetsMapping.length) {
              src = `${src};self.__offline_assets = ${JSON.stringify(offlineAssetsMapping)}`;
            }

            if (variables) {
              src = `${src};self.__injected_variables = ${JSON.stringify(variables)};`;
            }
            if (text && text.length) {
              src = `${src};${text}`;
            }

            compilation.assets[fileName] = {
              source: function source() {
                return src;
              },
              size: function size() {
                return src.length;
              }
            };
          }
        });
      }
    }

    module.exports = SwVariables;