FileUriPlugin.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. const PLUGIN_NAME = "FileUriPlugin";
  10. class FileUriPlugin {
  11. /**
  12. * Apply the plugin
  13. * @param {Compiler} compiler the compiler instance
  14. * @returns {void}
  15. */
  16. apply(compiler) {
  17. compiler.hooks.compilation.tap(
  18. PLUGIN_NAME,
  19. (compilation, { normalModuleFactory }) => {
  20. normalModuleFactory.hooks.resolveForScheme
  21. .for("file")
  22. .tap(PLUGIN_NAME, resourceData => {
  23. const url = new URL(resourceData.resource);
  24. const path = fileURLToPath(url);
  25. const query = url.search;
  26. const fragment = url.hash;
  27. resourceData.path = path;
  28. resourceData.query = query;
  29. resourceData.fragment = fragment;
  30. resourceData.resource = path + query + fragment;
  31. return true;
  32. });
  33. const hooks = NormalModule.getCompilationHooks(compilation);
  34. hooks.readResource
  35. .for(undefined)
  36. .tapAsync(PLUGIN_NAME, (loaderContext, callback) => {
  37. const { resourcePath } = loaderContext;
  38. loaderContext.addDependency(resourcePath);
  39. loaderContext.fs.readFile(resourcePath, callback);
  40. });
  41. }
  42. );
  43. }
  44. }
  45. module.exports = FileUriPlugin;