3 tips to make importing more compact in ES6

Tram Ho

Hello everyone, at the beginning of the year, I wish you a new year full of health, happiness with your family and working effectively, reaping many successes in life.

Introduce

In normal Javascript projects, where do you usually use and import? Or if it’s clearer, split the import lines by different definition or function Screen Shot 2023-01-31 at 21.06.15.png With the above example, there are only a few lines, but if you use a lot of functions, variables or components from other folders, only the import lines have reached more than 50 lines To overcome this problem, today I share with you Do you have a few tips to make the import lines look neater and cleaner?

There are 3 neat import tips

1. Barrel Pattern is the grouping of many individual components (A, B, C, D, …) in a single file One, so just import to file One and then call other components to use it.

  • Create an index.js file in the columns . folder Screen Shot 2023-01-31 at 21.24.00.png
  • Using componenet in other files Screen Shot 2023-01-31 at 21.26.18.png So with only a single composite file, files using components can be imported more succinctly. Using aliases As shown at the beginning of the article, after each word, there are many punctuation marks. and the / looks very confusing. Like v, you need to set up alias, alias has the following benefits:
  • shorten each import line
  • when importing in different files but the string after from is unchanged Download this package to npm i babel-plugin-module-resolver or yarn add babel-plugin-module-resolver. There are 2 types without using Typscript and using Typescript Without using Typescript Create file babel.config.js and add these lines Screen Shot 2023-01-31 at 21.41.10.png Using Typescript Use the library Prettier plugin sort imports: https://github.com/trivago/prettier-plugin-sort-imports It will transfer: Screen Shot 2023-01-31 at 21.54.16.png Wall Screen Shot 2023-01-31 at 21.54.46.png

With the above 3 tips, your import lines will become much more beautiful and compact. And finally, I wish you all a very successful new year.

Share the news now

Source : Viblo