FileUriPlugin.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { URL, fileURLToPath } = require("url");
  7. const { NormalModule } = require("..");
  8. /** @typedef {import("../Compiler")} Compiler */
  9. class FileUriPlugin {
  10. /**
  11. * Apply the plugin
  12. * @param {Compiler} compiler the compiler instance
  13. * @returns {void}
  14. */
  15. apply(compiler) {
  16. compiler.hooks.compilation.tap(
  17. "FileUriPlugin",
  18. (compilation, { normalModuleFactory }) => {
  19. normalModuleFactory.hooks.resolveForScheme
  20. .for("file")
  21. .tap("FileUriPlugin", resourceData => {
  22. const url = new URL(resourceData.resource);
  23. const path = fileURLToPath(url);
  24. const query = url.search;
  25. const fragment = url.hash;
  26. resourceData.path = path;
  27. resourceData.query = query;
  28. resourceData.fragment = fragment;
  29. resourceData.resource = path + query + fragment;
  30. return true;
  31. });
  32. const hooks = NormalModule.getCompilationHooks(compilation);
  33. hooks.readResource
  34. .for(undefined)
  35. .tapAsync("FileUriPlugin", (loaderContext, callback) => {
  36. const { resourcePath } = loaderContext;
  37. loaderContext.addDependency(resourcePath);
  38. loaderContext.fs.readFile(resourcePath, callback);
  39. });
  40. }
  41. );
  42. }
  43. }
  44. module.exports = FileUriPlugin;