injectRefreshLoader.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const path = require('path');
  2. /**
  3. * @callback MatchObject
  4. * @param {string} [str]
  5. * @returns {boolean}
  6. */
  7. const resolvedLoader = require.resolve('../../loader');
  8. /**
  9. * Injects refresh loader to all JavaScript-like and user-specified files.
  10. * @param {*} data Module factory creation data.
  11. * @param {MatchObject} matchObject A function to include/exclude files to be processed.
  12. * @returns {*} The injected module factory creation data.
  13. */
  14. function injectRefreshLoader(data, matchObject) {
  15. if (
  16. // Include and exclude user-specified files
  17. matchObject(data.resource) &&
  18. // Skip plugin's runtime utils to prevent self-referencing -
  19. // this is useful when using the plugin as a direct dependency.
  20. !data.resource.includes(path.join(__dirname, '../runtime/RefreshUtils')) &&
  21. // Check to prevent double injection
  22. !data.loaders.find(({ loader }) => loader === resolvedLoader)
  23. ) {
  24. // As we inject runtime code for each module,
  25. // it is important to run the injected loader after everything.
  26. // This way we can ensure that all code-processing have been done,
  27. // and we won't risk breaking tools like Flow or ESLint.
  28. data.loaders.unshift({
  29. loader: resolvedLoader,
  30. options: undefined,
  31. });
  32. }
  33. return data;
  34. }
  35. module.exports = injectRefreshLoader;