Skip to content

Commit

Permalink
Merge pull request #26 from pmmmwh/fix/chunking
Browse files Browse the repository at this point in the history
fix: correctly inspect main templates to apply transform to JS runtime
  • Loading branch information
pmmmwh authored Dec 19, 2019
2 parents 4b6212f + 9317311 commit 615157e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
6 changes: 0 additions & 6 deletions src/helpers/createRefreshTemplate.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,6 @@ const afterModule = `
* @returns {string} A refresh-wrapped module.
*/
function createRefreshTemplate(source, chunk) {
// If a chunk is injected with the plugin,
// our custom entry for react-refresh musts be injected
if (!chunk.entryModule || !/ReactRefreshEntry/.test(chunk.entryModule._identifier || '')) {
return source;
}

const lines = source.split('\n');

// Webpack generates this line whenever the mainTemplate is called
Expand Down
32 changes: 31 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,37 @@ class ReactRefreshPlugin {
compilation.mainTemplate.hooks.require.tap(
this.constructor.name,
// Constructs the correct module template for react-refresh
createRefreshTemplate
(source, chunk, hash) => {
const mainTemplate = compilation.mainTemplate;

// Check for the output filename
// This is to ensure we are processing a JS-related chunk
let filename = mainTemplate.outputOptions.filename;
if (typeof filename === 'function') {
// Only usage of the `chunk` property is documented by Webpack.
// However, some internal Webpack plugins uses other properties,
// so we also pass them through to be on the safe side.
filename = filename({
chunk,
hash,
// TODO: Figure out whether we need to stub the following properties, probably no
contentHashType: 'javascript',
hashWithLength: length => mainTemplate.renderCurrentHashCode(hash, length),
noChunkHash: mainTemplate.useChunkHash(chunk),
});
}

// Check whether the current compilation is outputting to JS,
// since other plugins can trigger compilations for other file types too.
// If we apply the transform to them, their compilation will break fatally.
// One prominent example of this is the HTMLWebpackPlugin.
// If filename is falsy, something is terribly wrong and there's nothing we can do.
if (!filename || !filename.includes('.js')) {
return source;
}

return createRefreshTemplate(source, chunk);
}
);

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

0 comments on commit 615157e

Please sign in to comment.