loader-plugin-raw.jsm 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const { utils: Cu } = Components;
  6. const { NetUtil } = Cu.import("resource://gre/modules/NetUtil.jsm", {});
  7. /**
  8. * A function that can be used as part of a require hook for a
  9. * loader.js Loader. This function only handles webpack-style "raw!"
  10. * requires; other requires should not be passed to this. See
  11. * https://github.com/webpack/raw-loader.
  12. */
  13. this.requireRawId = function (id, require) {
  14. let uri = require.resolve(id.slice(4));
  15. // If the original string did not end with ".js", then
  16. // require.resolve might have added the suffix. We don't want to
  17. // add a suffix for a raw load (if needed the caller can specify it
  18. // manually), so remove it here.
  19. if (!id.endsWith(".js") && uri.endsWith(".js")) {
  20. uri = uri.slice(0, -3);
  21. }
  22. let stream = NetUtil.newChannel({
  23. uri: NetUtil.newURI(uri, "UTF-8"),
  24. loadUsingSystemPrincipal: true
  25. }).open2();
  26. let count = stream.available();
  27. let data = NetUtil.readInputStreamToString(stream, count, {
  28. charset: "UTF-8"
  29. });
  30. stream.close();
  31. // For the time being it doesn't seem worthwhile to cache the
  32. // result here.
  33. return data;
  34. };
  35. this.EXPORTED_SYMBOLS = ["requireRawId"];