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 Dec 2, 2024
1 parent 358fb8e commit 4010850
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 @@ -337,7 +337,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 hashBuilder = createHash( hashFunction );
Expand Down Expand Up @@ -387,6 +387,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 @@ -115,6 +115,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 @@ -340,6 +341,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 4010850

Please sign in to comment.