loader.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const path = require("path");
  2. const fs = require("fs");
  3. const { hackWrapLoaders } = require("./utils");
  4. let id = 0;
  5. const NS = path.dirname(fs.realpathSync(__filename));
  6. const getLoaderName = path => {
  7. const nodeModuleName = /\/node_modules\/([^\/]+)/.exec(path);
  8. return (nodeModuleName && nodeModuleName[1]) || "";
  9. };
  10. module.exports.pitch = function() {
  11. const callback = this[NS];
  12. const module = this.resourcePath;
  13. const loaderPaths = this.loaders
  14. .map(l => l.path)
  15. .filter(l => !l.includes("speed-measure-webpack-plugin"));
  16. // Hack ourselves to overwrite the `require` method so we can override the
  17. // loadLoaders
  18. hackWrapLoaders(loaderPaths, (loader, path) => {
  19. const loaderName = getLoaderName(path);
  20. const wrapFunc = func =>
  21. function() {
  22. const loaderId = id++;
  23. const almostThis = Object.assign({}, this, {
  24. async: function() {
  25. const asyncCallback = this.async.apply(this, arguments);
  26. return function() {
  27. callback({
  28. id: loaderId,
  29. type: "end",
  30. });
  31. return asyncCallback.apply(this, arguments);
  32. };
  33. }.bind(this)
  34. });
  35. callback({
  36. module,
  37. loaderName,
  38. id: loaderId,
  39. type: "start",
  40. });
  41. const ret = func.apply(almostThis, arguments);
  42. callback({
  43. id: loaderId,
  44. type: "end",
  45. });
  46. return ret;
  47. };
  48. if (loader.normal) loader.normal = wrapFunc(loader.normal);
  49. if (loader.default) loader.default = wrapFunc(loader.default);
  50. if (loader.pitch) loader.pitch = wrapFunc(loader.pitch);
  51. if (typeof loader === "function") return wrapFunc(loader);
  52. return loader;
  53. });
  54. };