最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to avoid duplicate dependencies in Gutenberg blocks

programmeradmin5浏览0评论

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?

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?

Share Improve this question edited Oct 8, 2020 at 14:09 bueltge 17.1k7 gold badges62 silver badges97 bronze badges asked Sep 14, 2020 at 6:21 GuerrillaGuerrilla 4156 silver badges20 bronze badges 2
  • Can you provide an example of the dependencies you're using? If they are not part of the ones that the plugin supports, you may need to add a custom webpack config that extends the one provided by @wordpress/scripts – Welcher Commented Oct 6, 2020 at 14:30
  • 2 "without having to re-create webpack build" - if I understand it correctly, no, you don't have to. You could put all your blocks in a single directory and use a single webpack config. As with the code duplication issue, webpack has a guide you can try. – Sally CJ Commented Oct 7, 2020 at 11:09
Add a comment  | 

1 Answer 1

Reset to default 2 +50

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
        }
      }
    } ),
  ]
}
发布评论

评论列表(0)

  1. 暂无评论