You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.3 KiB

4 years ago
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. var path = require('path');
  6. var loaderUtils = require("loader-utils");
  7. var validateOptions = require('schema-utils');
  8. module.exports = function () {};
  9. module.exports.pitch = function (request) {
  10. if (this.cacheable) this.cacheable();
  11. var options = loaderUtils.getOptions(this) || {};
  12. validateOptions(require('./options.json'), options, 'Style Loader (Useable)');
  13. options.hmr = typeof options.hmr === 'undefined' ? true : options.hmr;
  14. // The variable is needed, because the function should be inlined.
  15. // If is just stored it in options, JSON.stringify will quote
  16. // the function and it would be just a string at runtime
  17. var insertInto;
  18. if (typeof options.insertInto === "function") {
  19. insertInto = options.insertInto.toString();
  20. }
  21. // We need to check if it a string, or variable will be "undefined"
  22. // and the loader crashes
  23. if (typeof options.insertInto === "string") {
  24. insertInto = '"' + options.insertInto + '"';
  25. }
  26. var hmr = [
  27. // Hot Module Replacement
  28. "if(module.hot) {",
  29. " var lastRefs = module.hot.data && module.hot.data.refs || 0;",
  30. "",
  31. " if(lastRefs) {",
  32. " exports.ref();",
  33. " if(!content.locals) {",
  34. " refs = lastRefs;",
  35. " }",
  36. " }",
  37. "",
  38. " if(!content.locals) {",
  39. " module.hot.accept();",
  40. " }",
  41. "",
  42. " module.hot.dispose(function(data) {",
  43. " data.refs = content.locals ? 0 : refs;",
  44. "",
  45. " if(dispose) {",
  46. " dispose();",
  47. " }",
  48. " });",
  49. "}"
  50. ].join("\n");
  51. return [
  52. "var refs = 0;",
  53. "var dispose;",
  54. "var content = require(" + loaderUtils.stringifyRequest(this, "!!" + request) + ");",
  55. "var options = " + JSON.stringify(options) + ";",
  56. "options.insertInto = " + insertInto + ";",
  57. "",
  58. "if(typeof content === 'string') content = [[module.id, content, '']];",
  59. // Export CSS Modules
  60. "if(content.locals) exports.locals = content.locals;",
  61. "",
  62. "exports.use = exports.ref = function() {",
  63. " if(!(refs++)) {",
  64. " dispose = require(" + loaderUtils.stringifyRequest(this, "!" + path.join(__dirname, "lib", "addStyles.js")) + ")(content, options);",
  65. " }",
  66. "",
  67. " return exports;",
  68. "};",
  69. "",
  70. "exports.unuse = exports.unref = function() {",
  71. " if(refs > 0 && !(--refs)) {",
  72. " dispose();",
  73. " dispose = null;",
  74. " }",
  75. "};",
  76. options.hmr ? hmr : ""
  77. ].join("\n");
  78. };