How to avoid duplicate dependencies in Gutenberg blocks

The WordPress Gutenberg block build script uses wordpress/dependency-extraction-webpack-plugin to build the blocks without WordPress dependencies being repeated but what about other dependencies?

If I build a plugin with 10 blocks and they all re-use dependencies, the WordPress build script will embed the dependency in every block bundle.

Is there a good way to handle this without having to re-create webpack build by myself?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

WordPress Dependency extraction plugin @wordpress/dependency-extraction-webpack-plugin basically makes your ES6 dependency imports use WordPress scripts instead of adding them to the bundle over and over.

This makes modules registered and enqueued in WordPress (including but not limited to jquery, moment and react and wp.* modules) to be properly excluded from builds.

You can add additional dependencies to be excluded (make sure you register/enqueue in WordPress) with requestToHandle callback.

For example for excluding say react-sortable component from build registered as react-sortable script in WordPress (PHP),

module.exports = {
  plugins: [
    new DependencyExtractionWebpackPlugin( {
      requestToHandle: function ( module ) {
        if ( module === 'react-sortable' ) {
          return 'react-sortable'; // WordPress script handle
        }
      }
    } ),
  ]
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x