Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Modules: Exporting and importing performance differences

I have some components in my vue project. I don't like import loader from '@/components/someComponent1/someComponent1.vue'; because it's a lot to write and I have to repeat it for every component. So I wrote an index.jsfor the components folder:

export { default as someComponent1 } from './someComponent1/someComponent1.vue';
export { default as someComponent2 } from './someComponent2/someComponent2.vue';
...

This will allow me to import multiple components in one line:

import { someComponent1, someComponent2 } from '@/components';

My question: Is it possible that the index.js-ish-way is slower (and even maybe bad practice) than usual imports? I wonder because doing as in the example above 'loads' the whole exported object and destructures it, which isn't the case with 'normal' imports.

like image 943
sandrooco Avatar asked Oct 26 '17 15:10

sandrooco


People also ask

Should I use module exports or exports?

When we want to export a single class/variable/function from one module to another module, we use the module. exports way. When we want to export multiple variables/functions from one module to another, we use exports way.

Do unused imports affect performance JavaScript?

Unused imports have no performance impact at runtime.

Is it better to use require or import?

require statements have this flexibility because they are treated as functions. They are called at the run time, and there is no way to know anything before that. But, import statements are static, and we can't use them conditionally or dynamically. Note: You might see this as an advantage of require .

Should I use export default or export?

Exports without a default tag are Named exports. Exports with the default tag are Default exports. Using one over the other can have effects on your code readability, file structure, and component organization. Named and Default exports are not React-centric ideas.


1 Answers

No, it's not slower (not by much, of course it has to load one more file, and the IO will take most of the extra time).

An import always loads the whole module, creates all the exported values, and resolves the imported bindings. It doesn't matter whether only one or all the exported bindings are used. It doesn't matter what syntax the import declaration is using. It doesn't even matter whether the resolution goes through the additional index.js file or not, in the end the reference that is used at runtime is exactly the same.

On the contrary, I would consider it a good practise to use such an index.js file if it keeps your modules more maintainable.

like image 191
Bergi Avatar answered Oct 12 '22 08:10

Bergi