Search code examples
reactjswebpackcreate-react-app

Create a custom decorator "@" to import a module from it's parent directory (ReactJs)


I'd like to import a module from a directory using a custom decorator/annotation like @material-ui/core module, like the example below :

Instead of classic import

import class1 from '../../../../Services/module1';

I'd like to use this syntaxe

import class1 from '@Services/module1';

Thank's for your help !


Solution

  • I suggest using babel-plugin-module-resolver

    Specify the plugin in your .babelrc with the custom root or alias. Here's an example:

    {
      "plugins": [
        ["module-resolver", {
          "root": ["./src"],
          "alias": {
            "~": "./app",
            "underscore": "lodash"
          }
        }]
      ]
    }