woocommerce/plugins/woocommerce-blocks/bin/add-split-chunk-dependencie...

76 lines
2.3 KiB
JavaScript

// The Dependency Extraction Webpack Plugin does not add split chunks as dependencies
// to the .asset.php files that list dependencies. In the past we manually enqueued
// those dependencies in PHP.
// For every generated .asset.php file in the whole bundle, this plugin prefixes the
// list of dependencies with the handles of split chunks that were generated in the build.
// e.g. if your bundle has a vendors script called foo-vendors then for every entry-point
// that has a .asset.php file generated by Dependency Extraction Webpack Plugin
// the plugin will edit that file to include foo-vendors as a listed dependency.
// This means for any split chunk you build you'll only need to register it in PHP, but all
// files that depend on it will automatically include it as a dependency.
class AddSplitChunkDependencies {
apply( compiler ) {
compiler.hooks.thisCompilation.tap(
'AddStableChunksToAssets',
( compilation ) => {
compilation.hooks.processAssets.tap(
{
name: 'AddStableChunksToAssets',
stage: compiler.webpack.Compilation
.PROCESS_ASSETS_STAGE_ANALYSE,
},
() => {
const { chunks } = compilation;
const splitChunks = chunks.filter( ( chunk ) => {
return chunk?.chunkReason?.includes( 'split' );
} );
// find files that have an asset.php file
const chunksToAddSplitsTo = chunks.filter(
( chunk ) => {
return (
! chunk?.chunkReason?.includes( 'split' ) &&
chunk.files.find( ( file ) =>
file.endsWith( 'asset.php' )
)
);
}
);
for ( const chunk of chunksToAddSplitsTo ) {
const assetFile = chunk.files.find( ( file ) =>
file.endsWith( 'asset.php' )
);
const assetFileContent = compilation.assets[
assetFile
]
.source()
.toString();
const extraDependencies = splitChunks
.map( ( c ) => `'${ c.name }'` )
.join( ', ' );
const updatedFileContent = assetFileContent.replace(
/('dependencies'\s*=>\s*array\s*\(\s*)([^)]*)\)/,
`$1${ extraDependencies }, $2)`
);
compilation.assets[ assetFile ] = {
source: () => updatedFileContent,
size: () => updatedFileContent.length,
};
}
}
);
}
);
}
}
module.exports = AddSplitChunkDependencies;