index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. const { validate: validateOptions } = require('schema-utils');
  2. const { getRefreshGlobalScope, getWebpackVersion } = require('./globals');
  3. const {
  4. getAdditionalEntries,
  5. getIntegrationEntry,
  6. getRefreshGlobal,
  7. getSocketIntegration,
  8. injectRefreshEntry,
  9. injectRefreshLoader,
  10. makeRefreshRuntimeModule,
  11. normalizeOptions,
  12. } = require('./utils');
  13. const schema = require('./options.json');
  14. class ReactRefreshPlugin {
  15. /**
  16. * @param {import('./types').ReactRefreshPluginOptions} [options] Options for react-refresh-plugin.
  17. */
  18. constructor(options = {}) {
  19. validateOptions(schema, options, {
  20. name: 'React Refresh Plugin',
  21. baseDataPath: 'options',
  22. });
  23. /**
  24. * @readonly
  25. * @type {import('./types').NormalizedPluginOptions}
  26. */
  27. this.options = normalizeOptions(options);
  28. }
  29. /**
  30. * Applies the plugin.
  31. * @param {import('webpack').Compiler} compiler A webpack compiler object.
  32. * @returns {void}
  33. */
  34. apply(compiler) {
  35. // Skip processing in non-development mode, but allow manual force-enabling
  36. if (
  37. // Webpack do not set process.env.NODE_ENV, so we need to check for mode.
  38. // Ref: https://github.com/webpack/webpack/issues/7074
  39. (compiler.options.mode !== 'development' ||
  40. // We also check for production process.env.NODE_ENV,
  41. // in case it was set and mode is non-development (e.g. 'none')
  42. (process.env.NODE_ENV && process.env.NODE_ENV === 'production')) &&
  43. !this.options.forceEnable
  44. ) {
  45. return;
  46. }
  47. const webpackVersion = getWebpackVersion(compiler);
  48. const logger = compiler.getInfrastructureLogger(this.constructor.name);
  49. // Get Webpack imports from compiler instance (if available) -
  50. // this allow mono-repos to use different versions of Webpack without conflicts.
  51. const webpack = compiler.webpack || require('webpack');
  52. const {
  53. DefinePlugin,
  54. EntryDependency,
  55. EntryPlugin,
  56. ModuleFilenameHelpers,
  57. NormalModule,
  58. ProvidePlugin,
  59. RuntimeGlobals,
  60. Template,
  61. } = webpack;
  62. // Inject react-refresh context to all Webpack entry points.
  63. // This should create `EntryDependency` objects when available,
  64. // and fallback to patching the `entry` object for legacy workflows.
  65. const addEntries = getAdditionalEntries({
  66. devServer: compiler.options.devServer,
  67. options: this.options,
  68. });
  69. if (EntryPlugin) {
  70. // Prepended entries does not care about injection order,
  71. // so we can utilise EntryPlugin for simpler logic.
  72. addEntries.prependEntries.forEach((entry) => {
  73. new EntryPlugin(compiler.context, entry, { name: undefined }).apply(compiler);
  74. });
  75. const integrationEntry = getIntegrationEntry(this.options.overlay.sockIntegration);
  76. const socketEntryData = [];
  77. compiler.hooks.make.tap(
  78. { name: this.constructor.name, stage: Number.POSITIVE_INFINITY },
  79. (compilation) => {
  80. // Exhaustively search all entries for `integrationEntry`.
  81. // If found, mark those entries and the index of `integrationEntry`.
  82. for (const [name, entryData] of compilation.entries.entries()) {
  83. const index = entryData.dependencies.findIndex(
  84. (dep) => dep.request && dep.request.includes(integrationEntry)
  85. );
  86. if (index !== -1) {
  87. socketEntryData.push({ name, index });
  88. }
  89. }
  90. }
  91. );
  92. // Overlay entries need to be injected AFTER integration's entry,
  93. // so we will loop through everything in `finishMake` instead of `make`.
  94. // This ensures we can traverse all entry points and inject stuff with the correct order.
  95. addEntries.overlayEntries.forEach((entry, idx, arr) => {
  96. compiler.hooks.finishMake.tapPromise(
  97. { name: this.constructor.name, stage: Number.MIN_SAFE_INTEGER + (arr.length - idx - 1) },
  98. (compilation) => {
  99. // Only hook into the current compiler
  100. if (compilation.compiler !== compiler) {
  101. return Promise.resolve();
  102. }
  103. const injectData = socketEntryData.length ? socketEntryData : [{ name: undefined }];
  104. return Promise.all(
  105. injectData.map(({ name, index }) => {
  106. return new Promise((resolve, reject) => {
  107. const options = { name };
  108. const dep = EntryPlugin.createDependency(entry, options);
  109. compilation.addEntry(compiler.context, dep, options, (err) => {
  110. if (err) return reject(err);
  111. // If the entry is not a global one,
  112. // and we have registered the index for integration entry,
  113. // we will reorder all entry dependencies to our desired order.
  114. // That is, to have additional entries DIRECTLY behind integration entry.
  115. if (name && typeof index !== 'undefined') {
  116. const entryData = compilation.entries.get(name);
  117. entryData.dependencies.splice(
  118. index + 1,
  119. 0,
  120. entryData.dependencies.splice(entryData.dependencies.length - 1, 1)[0]
  121. );
  122. }
  123. resolve();
  124. });
  125. });
  126. })
  127. ).then(() => {});
  128. }
  129. );
  130. });
  131. } else {
  132. compiler.options.entry = injectRefreshEntry(compiler.options.entry, addEntries);
  133. }
  134. // Inject necessary modules and variables to bundle's global scope
  135. const refreshGlobal = getRefreshGlobalScope(RuntimeGlobals || {});
  136. /** @type {Record<string, string | boolean>}*/
  137. const definedModules = {
  138. // Mapping of react-refresh globals to Webpack runtime globals
  139. $RefreshReg$: `${refreshGlobal}.register`,
  140. $RefreshSig$: `${refreshGlobal}.signature`,
  141. 'typeof $RefreshReg$': 'function',
  142. 'typeof $RefreshSig$': 'function',
  143. // Library mode
  144. __react_refresh_library__: JSON.stringify(
  145. Template.toIdentifier(
  146. this.options.library ||
  147. compiler.options.output.uniqueName ||
  148. compiler.options.output.library
  149. )
  150. ),
  151. };
  152. /** @type {Record<string, string>} */
  153. const providedModules = {
  154. __react_refresh_utils__: require.resolve('./runtime/RefreshUtils'),
  155. };
  156. if (this.options.overlay === false) {
  157. // Stub errorOverlay module so their calls can be erased
  158. definedModules.__react_refresh_error_overlay__ = false;
  159. definedModules.__react_refresh_polyfill_url__ = false;
  160. definedModules.__react_refresh_socket__ = false;
  161. } else {
  162. definedModules.__react_refresh_polyfill_url__ = this.options.overlay.useURLPolyfill || false;
  163. if (this.options.overlay.module) {
  164. providedModules.__react_refresh_error_overlay__ = require.resolve(
  165. this.options.overlay.module
  166. );
  167. }
  168. if (this.options.overlay.sockIntegration) {
  169. providedModules.__react_refresh_socket__ = getSocketIntegration(
  170. this.options.overlay.sockIntegration
  171. );
  172. }
  173. }
  174. new DefinePlugin(definedModules).apply(compiler);
  175. new ProvidePlugin(providedModules).apply(compiler);
  176. const match = ModuleFilenameHelpers.matchObject.bind(undefined, this.options);
  177. let loggedHotWarning = false;
  178. compiler.hooks.compilation.tap(
  179. this.constructor.name,
  180. (compilation, { normalModuleFactory }) => {
  181. // Only hook into the current compiler
  182. if (compilation.compiler !== compiler) {
  183. return;
  184. }
  185. // Tap into version-specific compilation hooks
  186. switch (webpackVersion) {
  187. case 4: {
  188. const outputOptions = compilation.mainTemplate.outputOptions;
  189. compilation.mainTemplate.hooks.require.tap(
  190. this.constructor.name,
  191. // Constructs the module template for react-refresh
  192. (source, chunk, hash) => {
  193. // Check for the output filename
  194. // This is to ensure we are processing a JS-related chunk
  195. let filename = outputOptions.filename;
  196. if (typeof filename === 'function') {
  197. // Only usage of the `chunk` property is documented by Webpack.
  198. // However, some internal Webpack plugins uses other properties,
  199. // so we also pass them through to be on the safe side.
  200. filename = filename({
  201. contentHashType: 'javascript',
  202. chunk,
  203. hash,
  204. });
  205. }
  206. // Check whether the current compilation is outputting to JS,
  207. // since other plugins can trigger compilations for other file types too.
  208. // If we apply the transform to them, their compilation will break fatally.
  209. // One prominent example of this is the HTMLWebpackPlugin.
  210. // If filename is falsy, something is terribly wrong and there's nothing we can do.
  211. if (!filename || !filename.includes('.js')) {
  212. return source;
  213. }
  214. // Split template source code into lines for easier processing
  215. const lines = source.split('\n');
  216. // Webpack generates this line when the MainTemplate is called
  217. const moduleInitializationLineNumber = lines.findIndex((line) =>
  218. line.includes('modules[moduleId].call(')
  219. );
  220. // Unable to find call to module execution -
  221. // this happens if the current module does not call MainTemplate.
  222. // In this case, we will return the original source and won't mess with it.
  223. if (moduleInitializationLineNumber === -1) {
  224. return source;
  225. }
  226. const moduleInterceptor = Template.asString([
  227. `${refreshGlobal}.setup(moduleId);`,
  228. 'try {',
  229. Template.indent(lines[moduleInitializationLineNumber]),
  230. '} finally {',
  231. Template.indent(`${refreshGlobal}.cleanup(moduleId);`),
  232. '}',
  233. ]);
  234. return Template.asString([
  235. ...lines.slice(0, moduleInitializationLineNumber),
  236. '',
  237. outputOptions.strictModuleExceptionHandling
  238. ? Template.indent(moduleInterceptor)
  239. : moduleInterceptor,
  240. '',
  241. ...lines.slice(moduleInitializationLineNumber + 1, lines.length),
  242. ]);
  243. }
  244. );
  245. compilation.mainTemplate.hooks.requireExtensions.tap(
  246. this.constructor.name,
  247. // Setup react-refresh globals as extensions to Webpack's require function
  248. (source) => {
  249. return Template.asString([source, '', getRefreshGlobal(Template)]);
  250. }
  251. );
  252. normalModuleFactory.hooks.afterResolve.tap(
  253. this.constructor.name,
  254. // Add react-refresh loader to process files that matches specified criteria
  255. (data) => {
  256. return injectRefreshLoader(data, {
  257. match,
  258. options: { const: false, esModule: false },
  259. });
  260. }
  261. );
  262. compilation.hooks.normalModuleLoader.tap(
  263. // `Number.POSITIVE_INFINITY` ensures this check will run only after all other taps
  264. { name: this.constructor.name, stage: Number.POSITIVE_INFINITY },
  265. // Check for existence of the HMR runtime -
  266. // it is the foundation to this plugin working correctly
  267. (context) => {
  268. if (!context.hot && !loggedHotWarning) {
  269. logger.warn(
  270. [
  271. 'Hot Module Replacement (HMR) is not enabled!',
  272. 'React Refresh requires HMR to function properly.',
  273. ].join(' ')
  274. );
  275. loggedHotWarning = true;
  276. }
  277. }
  278. );
  279. break;
  280. }
  281. case 5: {
  282. // Set factory for EntryDependency which is used to initialise the module
  283. compilation.dependencyFactories.set(EntryDependency, normalModuleFactory);
  284. const ReactRefreshRuntimeModule = makeRefreshRuntimeModule(webpack);
  285. compilation.hooks.additionalTreeRuntimeRequirements.tap(
  286. this.constructor.name,
  287. // Setup react-refresh globals with a Webpack runtime module
  288. (chunk, runtimeRequirements) => {
  289. runtimeRequirements.add(RuntimeGlobals.interceptModuleExecution);
  290. runtimeRequirements.add(RuntimeGlobals.moduleCache);
  291. runtimeRequirements.add(refreshGlobal);
  292. compilation.addRuntimeModule(chunk, new ReactRefreshRuntimeModule());
  293. }
  294. );
  295. normalModuleFactory.hooks.afterResolve.tap(
  296. this.constructor.name,
  297. // Add react-refresh loader to process files that matches specified criteria
  298. (resolveData) => {
  299. injectRefreshLoader(resolveData.createData, {
  300. match,
  301. options: {
  302. const: compilation.runtimeTemplate.supportsConst(),
  303. esModule: this.options.esModule,
  304. },
  305. });
  306. }
  307. );
  308. NormalModule.getCompilationHooks(compilation).loader.tap(
  309. // `Infinity` ensures this check will run only after all other taps
  310. { name: this.constructor.name, stage: Infinity },
  311. // Check for existence of the HMR runtime -
  312. // it is the foundation to this plugin working correctly
  313. (context) => {
  314. if (!context.hot && !loggedHotWarning) {
  315. logger.warn(
  316. [
  317. 'Hot Module Replacement (HMR) is not enabled!',
  318. 'React Refresh requires HMR to function properly.',
  319. ].join(' ')
  320. );
  321. loggedHotWarning = true;
  322. }
  323. }
  324. );
  325. break;
  326. }
  327. default: {
  328. // Do nothing - this should be an impossible case
  329. }
  330. }
  331. }
  332. );
  333. }
  334. }
  335. module.exports.ReactRefreshPlugin = ReactRefreshPlugin;
  336. module.exports = ReactRefreshPlugin;