1

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 !

Mehdi Benmoha
  • 3,694
  • 3
  • 23
  • 43
AHmedRef
  • 2,555
  • 12
  • 43
  • 75
  • 1
    This is not a decorator or annotation. The use of incorrect terms doesn't help to get a correct answer. *like @material-ui/core module* - it's not anything like that. @material-ui is package scope, https://docs.npmjs.com/misc/scope . What you're trying to do is an alias, https://stackoverflow.com/questions/42749973/es6-import-using-at-sign-in-path-in-a-vue-js-project-using-webpack . It's very specific to your setup which wasn't explained. If you're using Webpack directly, that's one thing. If you're using CRA, it's another. – Estus Flask Feb 26 '19 at 17:34
  • @estus im using CRA – AHmedRef Feb 26 '19 at 19:50
  • Possible duplicate of https://stackoverflow.com/questions/50132624/how-to-add-import-shortcuts-alias . You may want to change Webpack config with react-app-rewired instead of ejecting CRA. – Estus Flask Feb 26 '19 at 20:06

3 Answers3

1

In TS:

"paths": {
      "@app/*": ["app/*"],
      "@env/*": ["environments/*"]
}

In the compilerOptions in your tsconfig.json file.

In Webpack: How can I use shortcut path "@" in webpack?

Mehdi Benmoha
  • 3,694
  • 3
  • 23
  • 43
1

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"
      }
    }]
  ]
}
Amine Hakkou
  • 554
  • 5
  • 14
0

I have to eject my reactJs project (created using CRA) -> edit webpack.config.js -> Add an alias :

  resolve: {
    extensions: ['.js', '.jsx'],
    alias: {
      '@pages': path.join(__dirname, '/src/pages'),
      '@components': path.join(__dirname, '/src/components'),
      '@assets': path.join(__dirname, '/src/assets'),
    },
  },
AHmedRef
  • 2,555
  • 12
  • 43
  • 75