如何正确使用webpack的ReplaceSource来优化某些模块?

时间:2018-04-25 15:36:42

标签: webpack webpack-plugin

我注意到构建中的模块中存在一些重复的代码。我想通过编写一个webpack插件来查找X代码的实例来优化我的JavaScript,并用简化版的Y代码替换它。

我已经制作了一个似乎很接近的简单webpack插件,但它并不能完全符合我的要求。关于正确使用webpack ReplaceSource的内容,甚至是正确的生命周期是什么样的文档都没有很多文档可以用来进行这种操作。所以我所拥有的主要是从阅读webpack源代码和围绕GitHub搜索拼凑而成。

const { ReplaceSource } = require('webpack-sources');

const codeMapEntries = Object.entries({
  'const from = "complicated code from example";': 'const from = somethingSimpler;',
});

class ReplaceCodePlugin {
  apply(compiler) {
    compiler.plugin('compilation', (compilation) => {
      compilation.plugin('optimize-modules', (modules) => {
        modules.forEach((module) => {
          if (module._source && module._source._value) {
            let source;

            codeMapEntries.forEach(([fromCode, toCode]) => {
              const startPos = module._source._value.indexOf(fromCode);
              if (startPos !== -1) {
                if (!source) {
                  source = new ReplaceSource(module._source);
                }

                source.replace(
                  startPos,
                  startPos + fromCode.length - 1,
                  toCode
                );
              }
            });

            if (source) {
              module._source = source;
            }
          }
        });
      });
    });
  }
}

module.exports = ReplaceCodePlugin;

对于一些简单的情况,这似乎有点工作,但是这里的某些东西是不正确的,它导致代码奇怪地混乱,然后导致我们的minifier抱怨这样:

SyntaxError: Unexpected token keyword «if», expected punc «,»
  3417 |   }, {
  3418 |     key: 'componentWillUnmount',
> 3419 |     value: ffalse  if (!Waypoint.getWindow()) {
       |                   ^
  3420 |           return;
  3421 |         }
  3422 | 

这让我相信我没有正确使用ReplaceSource

我也注意到了一些类似下面的代码,这看起来很奇怪:

var ___webpack_require__r"Jmof"= require('some-package');

var _somePackage2 = _interopRequir__webpack_require__t"yu5W"kage);

我甚至不确定这是否是正确的方法,并愿意接受替代解决方案的建议。

1 个答案:

答案 0 :(得分:1)

我能够通过使用optimize-chunk-assets编译钩子而不是optimize-modules编译钩子来完成这项工作。但是,我真的不明白为什么一个有效,另一个没有。作为参考,这是我的插件的工作版本:

const { ReplaceSource } = require('webpack-sources');

const codeMapEntries = Object.entries({
  'const from = "complicated code from example";': 'const from = somethingSimpler;',
});

class ReplaceCodePlugin {
  apply(compiler) {
    compiler.plugin('compilation', (compilation) => {
      compilation.plugin('optimize-chunk-assets', (chunks, callback) => {
        function getAllIndices(str, searchStr) {
          let i = -1;
          const indices = [];
          while ((i = str.indexOf(searchStr, i + 1)) !== -1) {
            indices.push(i);
          }
          return indices;
        }

        chunks.forEach((chunk) => {
          chunk.files.forEach((file) => {
            let source;
            const originalSource = compilation.assets[file];

            codeMapEntries.forEach(([fromCode, toCode]) => {
              const indices = getAllIndices(originalSource.source(), fromCode);
              if (!indices.length) {
                return;
              }

              if (!source) {
                source = new ReplaceSource(originalSource);
              }

              indices.forEach((startPos) => {
                const endPos = startPos + fromCode.length - 1;
                source.replace(startPos, endPos, toCode);
              });
            });

            if (source) {
              // eslint-disable-next-line no-param-reassign
              compilation.assets[file] = source;
            }

            callback();
          });
        });
      });
    });
  }
}

module.exports = ReplaceCodePlugin;
相关问题