create-react-app: Using the tsconfig file to configure the alias does not take effect

The project was generated using the create-react-app scaffolding, and the paths option was removed when I used the tsconfig.json file to configure the path alias! Then I tried to use the extends property in the tsconfig.json file to connect to the external path configuration file, but it didn’t work either! Using the customize-cra plug-in in conjunction with the above configuration file does not take effect. How do I configure it? Why doesn’t the scaffolding support?

React version: 16.13.1 react-scripts version: 3.4.1

{
  "extends": "./tsconfig.paths.json", // Subsequent configuration options
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

The tsconfig.paths. json path file configuration:

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@/*": ["src/*"],
      "actions/*": ["src/actions"],
      "api/*": ["src/api"],
      "common/*": ["src/common"],
      "components/*": ["src/components"],
      "containers/*": ["src/containers"],
      "helper/*": ["src/helper"],
      "icon/*": ["src/icon"],
      "reducers/*": ["src/reducers"]
    }
  }
}

Customize -cra configuration file:

const { override, addDecoratorsLegacy, addWebpackAlias } = require("customize-cra")
const path = require("path")

module.exports = override(
  addDecoratorsLegacy(),
  addWebpackAlias({
      "@": path.resolve(__dirname, 'src'),
      "actions": path.resolve(__dirname, 'src/actions'),
      "api": path.resolve(__dirname, 'src/api'),
      "common": path.resolve(__dirname, 'src/common'),
      "components": path.resolve(__dirname, 'src/components'),
      "containers": path.resolve(__dirname, 'src/containers'),
      "helper": path.resolve(__dirname, 'src/helper'),
      "icon": path.resolve(__dirname, 'src/icon'),
      "reducers": path.resolve(__dirname, 'src/reducers')
  })
)

Sample file contents: import App from 'components/App' Warning message:

The following changes are being made to your tsconfig.json file:
  - compilerOptions.paths must not be set (aliased imports are not supported)

Error message:

./src/index.tsx
Module not found: Can't resolve 'components/App' in 'D:\code\my-music\src'

Please help me thank you!

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 48
  • Comments: 44

Commits related to this issue

Most upvoted comments

It is definitely bad to modify user’s custom tsconfig.json without options!

I found a workaround:

Move current tsconfig.json to tsconfig.base.json, and add a new file tsconfig.json:

{
  "extends": "./tsconfig.base.json"
}

Is there at least a good reason for not allowing path aliases in CRA?

create-react-app doesn’t support path aliasing and probably won’t for the near future. Reference: https://github.com/facebook/create-react-app/issues/7795#issuecomment-541582032

The best alternative right now is to define "baseUrl": "." and prefix imports with src Example:

import { MyComponent } from "src/components"

@lnwu The editor is webstorm! The problem has been resolved and you need to install react-app-rewired and configure both the ts path alias Settings and the webpack alias Settings

I just tried it (again). The code completion in VSCode works for those paths, but it won’t compile and outputs the following error message:

Module not found: Can't resolve '@components/layout/ToggleSection' in '/Users/chris/app/src/pages/Perspectives'

Interestingly, when I restart my react app via npm run start, I briefly see the following message before compilation starts:

image

So it doesn’t work for me with "react-scripts": "4.0.3".

It could be nice to write why, and at least write in the advanced usage that you can’t do it. Or maybe add a section in the advanced usages with the list of what you can’t do.

Deleting the paths section in the tsconfig is really disturbing, the first time I didn’t know why my code was deleted because once the application is built the console is cleared.

It is definitely bad to modify user’s custom tsconfig.json without options! I found a workaround: Move current tsconfig.json to tsconfig.base.json, and add a new file tsconfig.json:

{
  "extends": "./tsconfig.base.json"
}

Thanks it works for me. I used it to refer the types module for ploty.js dist package.

Can you please send me your configuration file, I’m trying to set an alias for my images folder but cra isn’t even detecting files called with the base url. I’m not using any external tools btw, I’m just editing tsconfig in a new cra

// tsconfig.paths.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}
// tsconfig.json
{
  // all the other config...
  "extends": "./tsconfig.paths.json"
}

This worked once I also installed craco (npm i @craco/craco) and set up a craco.config.js file:

// craco.config.js
const path = require("path");
module.exports = {
  webpack: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
};

Finally, replace react-scripts with craco in package.json:

  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "craco eject"
  }

NOTE: you will still get a warning in the console, but it works. Not sure why such a standard practice is a hassle to configure. /shrug

@zaneclaes @chriszirkel

@ramishenouda what version of react-scripts and typescript are you using?

Is anybody aware of any workaround to get aliases working in CRA? I’ve tried this, but so far no luck. My symptoms are the same as the last poster, i.e., autocomplete validates the syntax but the react-scripts start results in a build failure.

TypeScript aliases work fine in CRA with a bit of help of craco. Basically:

We’ve been using this setup for more than a year now and we had absolutely no problems with it. It works on the latest version of CRA and the previous major version as well, TS 3.7+ (potentially earlier version as well).

I don’t think any of create-react-app team is going to comment on this, so I solved this by creating paths.json file

{
    "compilerOptions": {
        "baseUrl": "./src",
        "paths": {
            "@model/*": [
                "models/*"
            ],
            "@component/*": [
                "components/*"
            ]
        }
    }
}

and then extended it in the tsconfig.json file

.
.
"include": [
    "src"
  ],
  "extends": "./paths.json"
}

Doesn’t look like anyone from the create-react-app team is getting notifications on this since it was closed by stale bot. Further discussion should probably be continued in a new issue/feature-request, unless this one can be reopened.

It is definitely bad to modify user’s custom tsconfig.json without options! I found a workaround: Move current tsconfig.json to tsconfig.base.json, and add a new file tsconfig.json:

{
  "extends": "./tsconfig.base.json"
}

This worked for me! Used it for importing types from an adjacent package in a monorepo.

Unfortunately, this workaround is no longer working on cra@5 😦

It’s a bit hard to understand how something as basic as aliases are not supported by CRA. Even with CRACO it’s still cumbersome to get it working.

Just for future reference:

  • Using aliases may also be nice for TypeScript typings. (Like when using a limited bundle for Plotly, then for import Plotly from 'plotly.js-basic-dist' one could still use the typings of the full bundle. Not sure how to easily achieve that without aliased imports.)

  • When using "extends": "./tsconfig.base.json" I still get the same message, and my tsconfig.json is still changed (like: it’s pretty-formatted and comments are removed). But the extends is left untouched and is still effective. (For me, the TypeScript compiler no longer fails, and both npm test and npm run build work fine. 🥳)

It is definitely bad to modify user’s custom tsconfig.json without options!

I found a workaround:

Move current tsconfig.json to tsconfig.base.json, and add a new file tsconfig.json:

{
  "extends": "./tsconfig.base.json"
}

This worked for me! Used it for importing types from an adjacent package in a monorepo.

@lnwu If “src/” is added to each introduction, it is still not convenient, and it is better to use the shortest path. I am not sure why the create-react-app scaffolding removes the paths option when compiling, is this the default? For this reason, most people use react-app-rewired to change the path configuration!

Migrated CRA to Vite. Working very well.

Unfortunately, this workaround is no longer working on cra@5 😦

alias in CRA@5 works without any workaround. just modify the path config in tsconfig.json

I’m going to create an example here to reproduce the problem, but with my current project, it didn’t work. I end up using the react-app-rewired to override the settings.

Thank you; this worked, and saved me many hours. I had tried a different eject/alias tool (linked in the last post), but Craco did the trick. I specifically used the Use aliases from tsconfig.json (source: “tsconfig”) example from the craco-alias docs.

Do you guys still have the warning when building ? Even though aliases are working properly ?

The following changes are being made to your tsconfig.json file:
  - compilerOptions.paths must not be set (aliased imports are not supported)

Yes, but it doesn’t matter for us.

Update 2023, CRA still sucks. Not able to set the path as per my need. Tried the extends suggestion.

@MrBrN197 Switch to nextjs, it supports client side rendering.

It is definitely bad to modify user’s custom tsconfig.json without options!

I found a workaround:

Move current tsconfig.json to tsconfig.base.json, and add a new file tsconfig.json:

{
  "extends": "./tsconfig.base.json"
}

Thanks it works for me. I used it to refer the types module for ploty.js dist package.

@v4voloshyn I think you may be thinking of v5 as the latest version. It is latest but it is 2 years old and extends didn’t work for me in v5.

Unfortunately, this workaround is no longer working on cra@5 😦

alias in CRA@5 works without any workaround. just modify the path config in tsconfig.json

update: it works with craco, craco-alias. but craco is not fully support CRA@5 now.

@VitaminCtea This code worked for me.

stackoverflow.com Click on me

Thank you; this worked, and saved me many hours. I had tried a different eject/alias tool (linked in the last post), but Craco did the trick. I specifically used the Use aliases from tsconfig.json (source: “tsconfig”) example from the craco-alias docs.