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.
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.
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.
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
In the root of components
folder we need to define an index.js
file which will export all the components
defined in it.
The App
component is imported in the main index.js
file and the final result is this.
We can also use our import our components inside other component files using the same non-relative paths like this.
By using this way we can reduce our cleanly import our files.
Top comments (0)