ES6: Use export to Reuse a Code Block. Export question

When we want some code - a function, or a variable - to be usable in another file, we must export it in order to import it into another file.

Can someone explain export to me? When we want it usable in another file, why would I want this?

1 Like

I can try, sure.

Sometimes, it’s handy to have a whole bunch of functions or classes, but to have them all crammed into a single long javascript file would not only be ugly, it could get pretty un-maintainable. Before ES6 started offering this as a thing, we had to use libraries like require.js to do much the same thing.

It becomes a very useful tactic to group a number of like components into a single file. But, using ES6 import syntax, each file imported creates its own namespace. They don’t share a context, which is a GOOD thing - otherwise, any global variables I declared in my javascript file could overwrite those you were defining in YOURS. Assuming we were silly enough to use global variables. :wink:

Instead, we need a mechanism to get stuff OUT of that private namespace that each js import lives in, and to use it in our file that just imported it! If our object or class to be imported has actually exported something, then we can use that in our local namespace, without problems.

Another nice thing about import is, you can limit what you import to just what you need. React, for example, contains more than just react - as you see when you do

import { Component }, React from react;

That is importing TWO things: the first, Component, is being exported from within the react javascript file (the React namespace, if you like), so we can import it. It isn’t the default export, though, so we need to use the curly braces to explicitly name it.

The second import, React, is the default – within the react include file, there is a line that reads something like:

export default React;

… which means we DON’T need to use curly braces, we just get that… by default.

Thank you for your reply.

Basically, what export does?

1 Like

You have a function that is in one file (files are modules in JavaScript: one file === one module). You want to use it in another file. So you export it from the first file, then import it in the file you want to use it in.

Thanks for the reply.

I’ve built a few utility libraries in javascript. There are some functions in there, though, that are not intended for “public consumption” - they are there to make my utilities more useful, but they’re not something intended to be used anywhere else. Those, I don’t export.

The advantage of using import / export is, you can write your modules or includes with a LOT more code than the user may need, and only export (or make available) the functions you’d want accessible.