如何将JavaScript字符串添加到Webpack编译的每个模块中?

时间:2018-06-07 06:31:21

标签: javascript webpack webpack-2

我希望将JavaScript字符串添加到我的代码中所需的每个模块,并由Webpack编译。

例如,如果我的entry.js文件如下所示:

import _ from 'lodash';
import $ from 'jquery';
import init from './init.js';

init();

我希望我的output.js套装包含以下内容:

function(module, exports, __webpack_require__) {
  // prepended JavaScript goes here

  // code for lodash module below
}

function(module, exports, __webpack_require__) {
  // prepended JavaScript goes here

  // code for jquery module below
}

function(module, exports, __webpack_require__) {
  // prepended JavaScript goes here

  // code for init.js module below
}

function(module, exports, __webpack_require__) {
  // prepended JavaScript goes here

  var _lodash = __webpack_require__(1);
  var _jquery = __webpack_require__(2);

  init();
}

我尝试编写一个简单的加载程序,它起作用了,除了它没有包含来自node_modules的模块,因为我将/\.js$/规则中的模块排除在外。

所以我怀疑我需要使用插件。这就是我到目前为止所做的:

var pluginName = "PrependJSPlugin";

var apply = (options, compiler) => {
  compiler.hooks.compilation.tap(pluginName, compilation =>
    compilation.hooks.afterOptimizeModules.tap(pluginName, modules => {
      modules.forEach(mod => {
        if (mod.resource !== void 0 && mod.resource.includes(".js")) {
          var contId = "__WBP_PREPEND__";
          var script = `
            ;var el = document.createElement('pre');
            el.innerHTML = '${mod.resource}';

            var container = document.getElementById('${contId}');
            if (!container) {
              container = document.createElement('div');
              container.id = '${contId}';
              container.appendChild(el);
              document.getElementsByTagName('body')[0].appendChild(container);
            } else {
              container.appendChild(el);
            }
          `;
          mod._source._value = script + mod._source._value;
        }
      });
    })
  );
};

module.exports = function(options) {
  return {
    apply: apply.bind(this, options)
  };
};

在大多数情况下,似乎它正确地附加了它,但编译后的输出在某种程度上被破坏了,我看到了整个地方的语法错误。我确实在做一些我不应该使用_source财产的事情。

有人能指出我正确的方向吗?

为什么我要这样做?

这不会投入生产。我试图调试我用于从Angular页面渲染PDF的第三方服务中发生的PhantomJS v1错误。哎呀,我知道!

我使用window.onerror捕获错误并将其附加到正文中,以便它们显示在呈现的PDF中。不幸的是,错误不包括源文件或行号。所以我试图在运行之前显示每个模块的名称,希望看到JavaScript停止执行哪一个。

0 个答案:

没有答案