DEV Community

Cover image for How To use ES6 import & export in your project
Mohamed Amine Fh
Mohamed Amine Fh

Posted on

How To use ES6 import & export in your project

Hello Everyone, I hope you're doing well

So After that being said, let's start our blog, so in this blog you'll learn how to use the ES6 features on your client or server project

Frontend aka Client

You've an index.html file and some css and js files, and for most cases you want to separate your Javascript code into multiple files and just import the necessary code into your main file let's say script.js.

The old way is to link those files in your html file and your main js file linked the last,
for exp you have these js files

Enter fullscreen mode Exit fullscreen mode

and let's say your script.js is the main one, the anotherFile.js is depending on the utils.js and the utils.js is depending on keys.js (depending word here means, that file is importing some data or needing some data from the other file)

this is what it would look like on your html file (index.html) to make your code work

scripts tag

You probably said what is the problem , right?

so in our case here we have a few js files, imagine that you've a big project to work on and let's say 20 js files in your project

Panic gif

I feel you LOL,

so we need to find a Solution, Fortunately there is a solution

Using the ES6 imports & exports (You could use the old ES5 require, but here we'll use a more modern one)

Just we need one script file to include in our html file and in that javascript file we'll include all other features or codes from other files.

1st thing to do is making our file a module so we can use the ES6 features, and that it can be done with the type attribute in script tag

<script type="module" src="script.js"> </script>

and in your files you could export and import other function or anything like so

Export and import in ES6

And that's it for the frontend

Backend aka Server

for the server is by the package.json file (created with the npm init), in that file add a type key and module as its value like this

package.json file

Yeap That's very much it, you're all set up to use new ES6 feature and speed your development process


Top comments (0)