Absolute Imports in ReactJS

Viewed 453

I recently created a ReactJS application, however, I cannot get the babel module resolver to work. I did not start the project using CRA but npm init.

The error i'm getting is

Module not found: Error: Can't resolve '@src/components/Component' in '/Users/path/to/app/src'

This is my babel.config ts:

module.exports = {
    presets: ['@babel/preset-env', '@babel/react'],
    plugins: [
        [
            'module-resolver',
            {
                extensions: ['.ts', '.tsx', '.js'],
                root: ['.'],
                alias: {
                    '@src': './src',
                }
            }
        ]
    ]
};
In my tsconfig.json I also added the following lines:

  "paths": {
    "@src/*": ["./src/*"]
  },
  "include": ["src"]

And this is the babel module solver version from my package.json dev dependencies:

    "babel-plugin-module-resolver": "^4.1.0",

Does anyone know how to solve this issue?

1 Answers

If anyone is experiencing similar issues, I managed to make it work by using webpack for absolute imports, and I gave up on babel-module-resolver.

I just added the following in my webpack.config.ts:

    resolve: {
            extensions: ['.ts', '.tsx', '.js'],
            alias: {
                '@src': path.resolve(__dirname, 'src/'),
            }
    }

And the other part from my tsconfig that I posted above.

Related