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.

53 lines
1.4 KiB

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