Search code examples
javascriptreactjswebpackimportcreate-react-app

Set a global service for import in Create React App


Is it possible to somehow declare a jsx file as a global file or a directory for import? For example instead of:

import { Navigation } from '../../../../../../helpers/NavigationService';

do just:

import { Navigation } from 'NavigationService';

I've seen it's possible in webpack config, but I don't see this file in create-react-app. Can I use somehow package.json for that?


Solution

  • There are three ways to solve your issue:

    1. NODE_PATH (<- probably what you're looking for):

    You can define an environment variable NODE_PATH=src/ and then you can import your service like so import { Navigation } from 'helpers/NavigationService';. It'll will work but this is not necessary what's best in my opinion.

    1. No deep nesting: No nesting, means no issue of deep nesting in the first place. You can try having a file hierarchy similar to this:
    src/
      /helpers
      /components/
        /componentA/
          componentA
          relatedComponent
          otherRelatedComponent <- no need for nesting
        /componentB/
      ...
    
    1. The mono repo approach:

    Having an internal helper package and have it imported like import { Navigation } from 'myproject-helpers/NavigationService'; may be a good compromise