Clean React: Better Imports
JavaScript may be the worst programming language when it comes to import. And we all hate those 20 lines of imports we have to write in every React file.
That's why I decided to write this article.
The first 2 methods work in any node project
1) Index imports
If you have to import multiple components from a directory, you can use an index.js to group them into a single import statement.
Let's take this for example:
Here, we have to import multiple components from pages directory. To shorten the imports, we can create an index.js in pages/ and export the components from there.
It will look like this:
And now, we can import them from "./pages".
2) SCSS Imports
I personally don't like to import every SCSS file in JS components, so I create a main one, named "index.scss"(the name is not relevant like in the first method). And then, I import others SCSS modules in the main one.
Let's see an example.
Here we have a main SCSS and 3 modules in pages directory from style.
To import the modules in index we only have to write this line:
For my case it will look like this:
领英推荐
And now, I can import the index.scss wherever I want and the code wrote in the modules will be applied.
In my React projects, I use to import it in src/index.js, but it's just my preference.
3) Lazy import
Lazy import is a way to import React components exactly when you need and if you need.
I wrote an entire article about dynamic imports, the principle used by lazy React imports. You should check it if you don't know how it works.
For lazy imports we have to use two functions provided by React library:
And this is how they are used:
In my case, I import the Router component that I need and the other will never be downloaded if it will not be needed.
This way I reduce the memory usage of the app and the performance because React will not heap all the imports when the file will be rendered.
Thanks for reading my article!
Please, tell me what do you think about these ways to import files in React and other import ideas. :)
And leave a like if you find this useful, so others like you can benefit from it.
You can also find my articles on my website:?mariusatasiei.com/blog
Sources: SCSS, React and Diana Mazareanu
Content manager at Rybray.
4 个月Looks like alias
UI/UX Designer | Web Designer & Developer
3 年This is a great