How to clean up import statements in modules

Viewed 4206

I'm slowly learning how to break things up into components but my OCD is going mad on one particular one. I have a tab view containing lots of different cards / panels. Standard dashboard. However my import statements are growing quickly as I add new cards ( and redux actions ).

import { fetchUser, matchUser, stopMatchUser } from '../../actions/userAction'
import { fetchMatches } from '../../actions/matchAction'
import MatchingCard from '../../components/MatchingCard'
import MapCard from '../../components/MapCard'
import ImageCard from '../../components/ImageCard'
import DocumentCard from '../../components/DocumentCard'

What would be a standard pattern to tidy this up? Put all those classes in one file? I was going to create an import file but I'd still be in the same scenario of adding many imports?

Any advice would be appreciated.

6 Answers

If you're using Webpack, you can use its resolve.alias, you can set up aliases for your commonly-used folders (eg. src) so you're not writing these long relative paths.

You can set it up so you either do something like:

import Component from "@/components/my-component.js"

... where @ means your src folder, or simply just:

import Component from "components/my-component.js"

And this works no matter where you are in the folder structure because its an absolute path.

// webpack.config.js

module.exports = {
  //...
  resolve: {
    alias: {
      Utilities: path.resolve(__dirname, 'src/utilities/'),
      Templates: path.resolve(__dirname, 'src/templates/')
    }
  }
};

This might be overkill and a little unrelated but it is still a possible solution. For large projects that contain a lot of similar code I'm defining more and more of the UI as data.

const formFields = [
  { id: 'name', type: 'string' },
  { id: 'size', type: 'integer' },
  { id: 'isPublic', type: 'boolean' }
]

Based on the type it chooses what type of component to use (textfield, checkbox, etc) and imports it for me. This pushes the importing to a common helper function and dramatically reduces the number of import statements in the codebase.

Also, using the alias feature in webpack might make figuring out those paths easier. It also makes refactoring the folder structure much easier.

Related