gregberge / loadable-components

The recommended Code Splitting library for React ✂️✨
https://loadable-components.com
MIT License
7.7k stars 381 forks source link

Allow additional identifiers to be passed in to the babel plugin #966

Closed edkimmel closed 1 year ago

edkimmel commented 1 year ago

Summary

I would like to wrap loadable in my own higher order component functions. Loadable by default only injects a webpack chunk name for loadable and lazy, but can readily accept additional identifiers.

This PR allows us to rewrite

// Loadable
const LoadableHelpPage = loadable(() => import('./HelpPage'), {
  resolveComponent: components => components.HelpPage,
})
// Our custom HOC
const HelpPage = PageHOC(LoadableHelpPage, {...additional page props })

to

const HelpPage = LoadablePageHOC(() => import('./HelpPage'), 'HelpPage', { ...additional page props })

We actually have a separate HOC for modals, so we would not be able to simply rename LoadablePageHOC to loadable for the sake of the existing babel plugin. With the changes, we can specify additionalIdentifiers: [ 'LoadablePageHOC', 'LoadableModalHOC'] to transform both.

Test plan

New tests have been added that showcase the custom identifier being transformed or not, depending on babel options.

theKashey commented 1 year ago

Got your idea, the request seems quite familiar 👍 and look like the currently proposed way to implement own loadable - loadable-detection - is not working. At least looking at the code.

In short - a right move, but let's take one more step and perfect this solution so it would not backfire in a couple of years as I don't feel that replacing random functions is a very safe pattern. What about changing the configuration a little bit to replicate the current logic of "autodetecting" loadable imports, but for a custom function?

Ie additionalIdentifiers: [ 'LoadablePageHOC', 'LoadableModalHOC'] ⬇️

signatures: [ 
  {name:'LoadablePageHOC', from:'@myapp/loadable'},
  {name:'LoadableModalHOC', from:'@myapp/loadable'},
  {name:'default', from:'@loadable/components'}, // still support default way
]

One can also refactor the current logic "looking" for default import of loadable and named import of lazy to utilize the same configuration, with your ability to totally override default configuration

edkimmel commented 1 year ago

@theKashey Thank you for the review.

Your suggestions are great, I should hopefully have some time this week to make the changes.

theKashey commented 1 year ago

Amazing result 👍 Let's get it merged and I will update the documentation shortly after.

theKashey commented 1 year ago

Released as 5.16.0