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.

55 lines
1.4 KiB

4 years ago
  1. 'use strict';
  2. var compiler = require('@riotjs/compiler');
  3. var loaderUtils = require('loader-utils');
  4. /**
  5. * Generate the hmr code depending on the tag generated by the compiler
  6. * @param {string} path - stringified, quote-enclosed path to the component file
  7. * @returns {string} the code needed to handle the riot hot reload
  8. */
  9. function hotReload(path) {
  10. return `;(() => {
  11. if (module.hot) {
  12. const hotReload = require('@riotjs/hot-reload').default
  13. module.hot.accept()
  14. if (module.hot.data) {
  15. const component = require(${path}).default;
  16. hotReload(component)
  17. }
  18. }
  19. })()`
  20. }
  21. function index(source) {
  22. // parse the user query
  23. const query = loaderUtils.getOptions(this) || {};
  24. // normalise the query object in case of question marks
  25. const opts = Object.keys(query).reduce(function(acc, key) {
  26. acc[key.replace('?', '')] = query[key];
  27. return acc
  28. }, {});
  29. // compile and generate sourcemaps
  30. const {code, map} = compiler.compile(
  31. source,
  32. {
  33. ...opts,
  34. file: this.resourcePath
  35. }
  36. );
  37. // generate the output code
  38. // convert webpack's absolute path to a script-friendly string for hotReload
  39. const escapedPath = loaderUtils.stringifyRequest(this, this.resourcePath);
  40. const output = `${code}${opts.hot ? hotReload(escapedPath) : ''}`;
  41. // cache this module
  42. if (this.cacheable) this.cacheable();
  43. // return code and sourcemap
  44. this.callback(null, output, map);
  45. }
  46. module.exports = index;