DEV Community

Rahul Soni
Rahul Soni

Posted on

How to cleanly import your files.

We all have sometime imported files or components like this in multiple lines, this would be okay if there is only one component or file to be imported, but as the codebase grows, writing import statements for every single file would get tedious as we're just repeating ourselves.
components in multiple lines

We're importing the components using the relative paths by leaving the src folder and going into the components folder and then going into the specific component folder.

We could easily replace that by importing all the files from their respective folder in a single line like this using non-relative import.

single line import

relative and non-relative imports

Note: In the first image components are exported using default export and in the latter image non default export is used.

First we need to define jsconfig.json file in the root of our project.
jsconfig.json has compilerOptions object which sets the baseUrl to be the src folder for resolution of non-relative imports.
jsconfig.json file

Each component gets it's own folder because components have several files involved like css or sometimes even more so it makes sense to do have a separate folder for each one.
It would look something like this with the component file, a css file and index.js file for exporting the component
component example

component 1

css styles

index.js component 1

In the root of components folder we need to define an index.js file which will export all the components defined in it.

index.js components level

The App component is imported in the main index.js file and the final result is this.
final render

We can also use our import our components inside other component files using the same non-relative paths like this.

component imported inside other component

By using this way we can reduce our cleanly import our files.

Discussion (0)