Vue组件本地与全局导入的体积差异及Webpack重复打包疑问
Great question—this is a common point of confusion when working with Vue and Webpack, so let's break it down step by step.
Do global and local imports create different bundle sizes?
Yes, they absolutely can, and it all comes down to whether the component is actually used in your application:
- Global imports: When you register a component globally like this:
The component gets bundled into your main application bundle regardless of whether you ever use theVue.component('modal', require('./components/modal.vue'));<modal>tag anywhere. Even if you never render it, it's still taking up space in your final code. This can bloat your bundle if you register lots of globally unused components. - Local imports: When you import and register a component locally inside another component:
The component only gets bundled if the parent component itself is included in the bundle (e.g., if the parent is rendered somewhere in your app). Plus, if you're using a production build with tree shaking (which Vue CLI enables by default), if you register the component locally but never actually use the// Inside parent component import modal from './components/modal.vue' export default { components: { modal } }<modal>tag in the parent's template, Webpack can strip that unused component code out entirely—saving you even more space.
Does Webpack duplicate code when importing a component locally multiple times?
Nope! Webpack is smart enough to avoid this. Here's why:
Webpack maintains a module cache—every time you import a module (like your modal.vue component) using the exact same file path, Webpack recognizes it as the same module. It will bundle that component once and reuse that single copy wherever you import it.
The only time you'd see duplication is if you import the component via different paths (e.g., ./components/modal.vue in one file and ../components/modal.vue in another, even if they point to the same file) or if you have multiple versions of the component installed (unlikely with local files). As long as your import paths are consistent, Webpack will only include the component once in your final bundle.
So to sum up: Local imports give you better control over bundle size by only including components when they're needed, and Webpack won't duplicate code no matter how many times you import the same component locally.
内容的提问来源于stack exchange,提问作者Philipp Mochine

