2

我注意到在我的构建中跨模块存在一些重复的代码。我想通过编写一个 webpack 插件来优化我的 JavaScript,以查找 X 代码的实例并将其替换为简化版本的 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);

我什至不确定这是否是正确的方法,并对替代解决方案的建议持开放态度。

4

1 回答 1

3

我能够通过使用 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;
于 2018-04-25T19:25:19.457 回答