Skip to content

Commit

Permalink
Scripts: Make React Fast Refresh Work with multiple blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
gziolo committed Aug 30, 2024
1 parent d74df84 commit 32b640e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
11 changes: 10 additions & 1 deletion packages/dependency-extraction-webpack-plugin/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ class DependencyExtractionWebpackPlugin {
// `RealContentHashPlugin` after minification, but it only modifies
// already-produced asset filenames and the updated hash is not
// available to plugins.
const { hashFunction, hashDigest, hashDigestLength } =
const { hashFunction, hashDigest, hashDigestLength, uniqueName } =
compilation.outputOptions;

const contentHash = chunkFiles
Expand All @@ -302,6 +302,15 @@ class DependencyExtractionWebpackPlugin {
assetData.type = 'module';
}

if ( compilation.options?.optimization?.runtimeChunk !== false ) {
assetData.handle =
uniqueName +
'-' +
chunkJSFile
.replace( /\\/g, '/' )
.replace( jsExtensionRegExp, '' );
}

if ( combineAssets ) {
combinedAssetsData[ chunkJSFile ] = assetData;
continue;
Expand Down
28 changes: 27 additions & 1 deletion packages/scripts/config/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const CopyWebpackPlugin = require( 'copy-webpack-plugin' );
const webpack = require( 'webpack' );
const browserslist = require( 'browserslist' );
const MiniCSSExtractPlugin = require( 'mini-css-extract-plugin' );
const { basename, dirname, resolve } = require( 'path' );
const { basename, dirname, relative, resolve, sep } = require( 'path' );
const ReactRefreshWebpackPlugin = require( '@pmmmwh/react-refresh-webpack-plugin' );
const RtlCssPlugin = require( 'rtlcss-webpack-plugin' );
const TerserPlugin = require( 'terser-webpack-plugin' );
Expand Down Expand Up @@ -159,6 +159,7 @@ const baseConfig = {
optimization: {
// Only concatenate modules in production, when not analyzing bundles.
concatenateModules: isProduction && ! process.env.WP_BUNDLE_ANALYZER,
runtimeChunk: hasReactFastRefresh && 'single',
splitChunks: {
cacheGroups: {
style: {
Expand Down Expand Up @@ -381,6 +382,31 @@ const scriptConfig = {
}
} );

if ( hasReactFastRefresh ) {
const runtimePath = relative(
dirname( absoluteFrom ),
fromProjectRoot(
getWordPressSrcDirectory() +
sep +
'runtime.js'
)
);
const fields =
getBlockJsonScriptFields( blockJson );
for ( const [ fieldName ] of Object.entries(
fields
) ) {
blockJson[ fieldName ] = [
`file:${ runtimePath }`,
...( Array.isArray(
blockJson[ fieldName ]
)
? blockJson[ fieldName ]
: [ blockJson[ fieldName ] ] ),
];
}
}

return JSON.stringify( blockJson, null, 2 );
}

Expand Down

0 comments on commit 32b640e

Please sign in to comment.