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

标签 webpack webpack-plugin

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

我编写了一个简单的 webpack 插件,看起来很接近,但它并不能完全满足我的要求。没有太多关于正确使用 webpack 的 ReplaceSource 的文档,甚至没有为这种操作 Hook 的正确生命周期。所以我这里的内容主要是通过阅读 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;

这似乎适用于一些简单的情况,但这里有些地方不正确,它导致代码奇怪地困惑,然后导致我们的压缩器像这样提示:

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);

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

最佳答案

我能够通过使用优化 block Assets 编译 Hook 而不是优化模块编译 Hook 来完成这项工作。但是,我真的不明白为什么一个有效而另一个无效。作为引用,这是我的插件的工作版本:

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;

关于webpack - 如何正确使用webpack的ReplaceSource来优化一些模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50026242/

相关文章:

javascript - 用另一个函数替换一个函数的 webpack 插件

node.js - 在编译时将基于包名称的变量传递给 webpack 源

javascript - Angular CLI(ng --version)命令错误 TS 和 WebPack

javascript - 使用 webpack ProvidePlugin 全局导入 javascript 文件

webpack 4 禁用 uglifyjs-webpack-plugin

webpack - html-webpack-plugin如何与html-loader一起使用?

javascript - Webpack离线插件如何将资源添加到sw.js

javascript - 如何将 webpack 配置为 "serve"现有开发站点?

javascript - 我什么时候应该构建 'dist' 文件夹,什么时候不应该构建?

javascript - 使用vue + webpack加载图片