1

in any project with node.js, react, i set up the env variable:

NODE_PATH=src/

and then i can do imports like

import COLORS from 'Constants/Colors'

instead of

import COLORS from '../../../Constants/Colors'

I just started with react-native, with expo and am trying to find a solution for this.

I tried the same approach of adding the env variable and it doesn't work

André Alçada Padez
  • 10,987
  • 24
  • 67
  • 120

3 Answers3

2

Using the "Imports" property

As of March 2023, a good way to eliminate JavaScript relative paths is to use the imports property in package.json. For more information, please refer to this post:

In the codes below, #root is the project root.

(Please kindly upvote this answer and this post if they help you. Thanks!)

For CommonJS-style JavaScripts:

// package.json
{
  "imports": {
    "#root/*.js": "./*.js"
  }
}

// main.js:
const Source = require('#root/path/to/Source.js');

// Source.js:
module.exports = class Source {
  // ...
}

For ECMAScript-style JavaScripts:

// package.json:
{
  "type" : "module",
  "imports": {
    "#root/*.js": "./*.js"
  }
}

// main.js
import { Source } from '#root/path/to/Source.js';

// Source.js:
export class Source {
  // ...
}

Advantages:

  • No need to "import" or "require" any additional packages (No Babel.js, No Webpack, No RequireJS). After installing NodeJS, this method works out of the box.

  • IDE linkages work as expected (Ctrl-click a class name to jump directly to the source file. Also, moving the source file (by drag and drop) will automatically update the file path references. Tested on WebStorm 2022.3.2 and VS Code 1.76.2.)

  • Works with both .mjs (ECMAScript module system) and .cjs (CommonJS) file types. Please see this reference Post on .cjs and .mjs.

  • No need to modify with the reserved node_modules directory

  • No need to set up any linux file links at the OS level

howard_9
  • 413
  • 3
  • 15
1

You can use babel-plugin-module-resolver library to simplify your imports paths. It allows to write alias imports instead of complex relative paths.

Mahdi N
  • 2,128
  • 3
  • 17
  • 38
1

install babel-plugin-module-resolver by

yarn add babel-plugin-module-resolver

then add relative path in babel.config.js file like this

module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo', 'module:metro-react-native-babel-preset' ],
    plugins: [
            [
                'module-resolver',
                {
                    alias: {
                       '@company'     : './src/company.json',
                       '@components'     : './src/components'

                }
            }
            ]
        ]
  };
};

then you can use an absolute path like this

import TextLabel from './src/components/textLabel/index.js'

To

import TextLabel from '@components/textLabel/index.js'
Muhammad Numan
  • 23,222
  • 6
  • 63
  • 80