Skip to content

Commit 615157e

Browse files
authored
Merge pull request #26 from pmmmwh/fix/chunking
fix: correctly inspect main templates to apply transform to JS runtime
2 parents 4b6212f + 9317311 commit 615157e

File tree

2 files changed

+31
-7
lines changed

2 files changed

+31
-7
lines changed

src/helpers/createRefreshTemplate.js

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,6 @@ const afterModule = `
3131
* @returns {string} A refresh-wrapped module.
3232
*/
3333
function createRefreshTemplate(source, chunk) {
34-
// If a chunk is injected with the plugin,
35-
// our custom entry for react-refresh musts be injected
36-
if (!chunk.entryModule || !/ReactRefreshEntry/.test(chunk.entryModule._identifier || '')) {
37-
return source;
38-
}
39-
4034
const lines = source.split('\n');
4135

4236
// Webpack generates this line whenever the mainTemplate is called

src/index.js

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,37 @@ class ReactRefreshPlugin {
9494
compilation.mainTemplate.hooks.require.tap(
9595
this.constructor.name,
9696
// Constructs the correct module template for react-refresh
97-
createRefreshTemplate
97+
(source, chunk, hash) => {
98+
const mainTemplate = compilation.mainTemplate;
99+
100+
// Check for the output filename
101+
// This is to ensure we are processing a JS-related chunk
102+
let filename = mainTemplate.outputOptions.filename;
103+
if (typeof filename === 'function') {
104+
// Only usage of the `chunk` property is documented by Webpack.
105+
// However, some internal Webpack plugins uses other properties,
106+
// so we also pass them through to be on the safe side.
107+
filename = filename({
108+
chunk,
109+
hash,
110+
// TODO: Figure out whether we need to stub the following properties, probably no
111+
contentHashType: 'javascript',
112+
hashWithLength: length => mainTemplate.renderCurrentHashCode(hash, length),
113+
noChunkHash: mainTemplate.useChunkHash(chunk),
114+
});
115+
}
116+
117+
// Check whether the current compilation is outputting to JS,
118+
// since other plugins can trigger compilations for other file types too.
119+
// If we apply the transform to them, their compilation will break fatally.
120+
// One prominent example of this is the HTMLWebpackPlugin.
121+
// If filename is falsy, something is terribly wrong and there's nothing we can do.
122+
if (!filename || !filename.includes('.js')) {
123+
return source;
124+
}
125+
126+
return createRefreshTemplate(source, chunk);
127+
}
98128
);
99129

100130
compilation.hooks.finishModules.tap(this.constructor.name, modules => {

0 commit comments

Comments
 (0)