How to avoid duplicate dependencies in Gutenberg blocks

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
        }
      }
    } ),
  ]
}