简体   繁体   中英

Absolute Imports in ReactJS

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM