Import & export in ES6/Angular

Introduction

When seeing for the first time Angular application, you may spot at the top of the components ‘import’ statements. This is due to the fact that Angular heavily relies on JavaScript ES6 and the ‘imports’ are part of it.

But what exactly ‘import’ means? To answer that question first we need to ask another one: what is ‘export’? ‘Export’ in JavaScript ES6 is way of saying ‘make this code available for other modules’. And with that knowledge we can answer the previous question, ‘import’ is the opposite of ‘export’ and it gets code from other modules. Another important thing to precise is what exactly ‘module’ is? Module is simply a piece of JavaScript code. Developers usually split code into different modules to keep code easy to maintain.

Coding and examples

With knowledge from introduction we’re ready to study some code. Let’s say we’ve got file called ‘functions.ts’ with (as file name said) three different functions.

These are simple functions which basically just log in the browser console appropriate welcome word.

To use the first function in a component we need to add an ‘export’ word before the function statement.

And then we need to import that function in component.

Now we can fire that function for example on the button click. So let’s add it in the component view.

And in component logic.

Finally in browser console ‘Hello’ text should appear. Well done! This method is called ‘named export’. When importing a ‘named export’, you need to import an ‘export’ by name in curly braces.

But what if you want to import another function from the ‘functions.ts’ file?

Then in a component just add the name of this function into curly bracers.

And you’re good to go.

Sometimes you may need to import all functions from a file. That won’t be a problem, in that case you should use.

* (asterisk) means all, then you need to assign it to the some alias, in that case it’s ‘functions’.

There’s one more export method – ‘default export’.

When you don’t specify certain name (omit curly braces) of ‘import’, the ‘default export’ will be imported.

In the ‘default export’ you can use random alias for ‘import’.

This will fire the same function as previous example and log into browser console ‘Greetings’. Bear in mind that in one file there could be only one ‘default export’.

Conclusion

As you can see, ‘import’/’export’ is fairly straightforward stuff.  You just need to remember that there are different ‘export’ methods – ‘named’ and ‘default’. And keeping that in mind, ‘import’ statement will also differ. All depends what you want to be imported into a component.

Leave a Reply

Your email address will not be published. Required fields are marked *