Introduction to babel-plugin-import

· 2 min read

Due to bundle size issues, I’ve revisited babel-plugin-import. I wasn’t clear about this plugin before, so I’m organizing my understanding here.

Plugin Introduction

babel-plugin-import is a Babel plugin that supports modular imports. The functionality of the plugin is to convert full imports to on-demand imports based on configuration.

Problems Solved

  1. The import path is still for the full package, making paths shorter.
  2. On-demand importing, resulting in smaller bundle sizes.

Examples

As mentioned officially, classic examples are antd/lodash, though this actually refers more to older versions of antd and lodash.

antd

import { Button } from 'antd';

import Button from 'antd/lib/button';

Note that although we use antd and lodash as examples here, in reality, both packages no longer need babel-plugin-import.

  1. antd now supports tree shaking.
  2. lodash has released an ES version package lodash-es; switching to that package name enables tree shaking as well.

Does it Conflict with Tree Shaking?

Not all projects use babel-plugin-import. Why? Because there’s tree shaking.

Are the two in conflict? Not at all, but they have the same ultimate goal: on-demand loading/bundling. When component libraries and the like support tree shaking, the build tool itself will remove unused modules during bundling. Therefore, as long as the component library supports tree shaking, you can use on-demand loading without needing babel-plugin-import.

Looking at the submission time of the plugin and when webpack started supporting tree shaking, it makes sense why babel-plugin-import was needed before. Because tree shaking wasn’t supported at that time.

Below is the submission time of babel-plugin-import:

https://static.1991421.cn/2024/2024-09-18-161956.jpeg

While webpack’s support for tree shaking came in webpack v4, which was around 2019.

Conclusion

OK, that’s the analysis of babel-plugin-import.