In modern JS applications, unused module can be automatically removed by modular packaging tools. This process is called Tree Shaking. However, if you are already very familiar with it, you will find that it is not so perfect in reality. We still need some extra operations to achieve the best size optimization effect. Today, let's talk about a problem that ConfigProvider causes Tree Shaking to fail.
ConfigProvider and rc-field-form
In daily maintenance, we encountered some problems that using ConfigProvider would cause bundle size to increase:
The community also found the package that was incorrectly packaged while giving feedback rc-field-form. Here we directly borrow the illustration in the issue:
ConfigProvider provides global configuration capabilities, which also includes the custom template configuration of Form component verification information:
<ConfigProviderform={{ validateMessages }}/>
Since this feature dependents with the verification of the form, it is implemented by the FormProvider provided by the underlying rc-field-form. In antd, it will be aggregated with its own localized validateMessages:
// Sample only. Not real world code.
import{FormProvider}from'rc-field-form';
constConfigProvider=({ validateMessages, children })=>{
Meanwhile, FormProvider itself encapsulates the FormContext of rc-field-form, which causes more content of rc-field-form to be packaged after introducing FormProvider:
You may think, can we optimize it? If validateMessages is not configured, we will not call this FormProvider?
// Sample only. Not real world code.
import{FormProvider}from'rc-field-form';
constConfigProvider=({ validateMessages, children })=>{
Unfortunately, this is not possible. Tree Shaking is a static compilation process, and validateMessages is a runtime configuration. So in the packaging process, we cannot know whether validateMessages exists, so we cannot achieve this optimization.
Decompose Dependencies
We can adjust rc-field-form dependencies, so that FormProvider can be decoupled. But obviously, we should not rely on the adjustment of third-party libraries though rc-field-form is also maintained by us. We should solve this problem fundamentally, so that ConfigProvider no longer depends on FormProvider. The implementation is also very simple. Since this is unique to rc-field-form, we directly extract a Context, so that ConfigProvider no longer perceives FormProvider:
Tree Shaking provides an automated way to optimize bundle size, but we need to pay attention to some details. Otherwise, some dependencies may be incorrectly introduced. Thanks.