Does import create a new copy of imported library?
Asked Answered
P

1

8

I'm using webpack + vue-loader to create vuejs app. I have multiple .vue files for components. When I write something like this:

import _ from 'lodash'

inside the script part of ComponentA.vue and ComponentB.vue, does this create two separate copies of lodash or does it simply import a reference?

Podium answered 22/6, 2016 at 10:52 Comment(1)
If the identifier lodash points to the same module from both locations where you use it, then yes that module is only instantiated only once.Chiles
V
13

Importing any part of an ES6 module (default or named exports) produces an immutable binding.

CommonJS modules export values, while ES6 modules export immutable bindings. This blog post explains what that means.

[ Source: ES6 Module Exports ]

So the answer is no, it does not create a copy of the exports. The module is initialised once and each import will receive a reference to the same value.

Vertical answered 22/6, 2016 at 10:59 Comment(1)
And just to prevent any misunderstandings, using require() also won't result in any duplication. subsequent require's of the same module also get replaced with a reference to the same valueIntend

© 2022 - 2024 — McMap. All rights reserved.