Search code examples
reactjstypescriptimportaliastsconfig

tsconfig.json using alias for import not working


I have project with react ts. Recently I try to use alias for my imports. So for that I have edit my file tsconfig.json with this params :

tsconfig.json

and I change my path import in my file like so :

import { couleurQualite } from "../../utils/coloration";

to

import { couleurQualite } from "@utils/coloration";

When I move my cursor on import my IDE show that : IDE resolution path

So at this place I don't have any error. But when i start my projet with cmd : npm run start

I receive these errors

Module not found: Error: Can't resolve '@utils/coloration' in '/home/YYYY/XXXX/XXXX/XXXX/XXXX/src/components/items'

ERROR in ./src/components/items/ItemBadge.tsx 11:0-51

Module not found: Error: Can't resolve '@utils/coloration' in '/home/YYYY/XXXX/XXXX/XXXX/XXXX/src/components/items'

webpack compiled with 1 error

This is my project structure:

project structure

Someone can help me ?


Solution

  • Finally it working, thank @TmTrom your answer put me on the right way.

    Some precision : with create-react-app, I can't directly edit webpack.config.js, so I found this for have same result.

    1. add required module
    2. create config-overrides.js and add to it information :
    addWebpackAlias({
            ['@customName']: path.resolve(__dirname, 'src/directory')
        })
    

    you can also try this for rewrite webpack

    The two cases work for me

    EDIT : You can also edit file webpack.config.js, he is located : node_modules/react-scripts/config/webpack.config.js

    And in this option, you don't need install any other module.