Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using the tsconfig file to configure the alias does not take effect #8909

Closed
Tracked in #30
VitaminCtea opened this issue Apr 26, 2020 · 37 comments
Closed
Tracked in #30

Comments

@VitaminCtea
Copy link

VitaminCtea commented Apr 26, 2020

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!

@lnwu
Copy link

lnwu commented Apr 27, 2020

And the hit "compilerOptions.paths must not be set (aliased imports are not supported)"
will disable your paths settings, so vscode will not detect it even it works with Customize -cra.

@VitaminCtea
Copy link
Author

VitaminCtea commented Apr 27, 2020

@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

@lnwu
Copy link

lnwu commented Apr 28, 2020

Found that can do it just using baseurl in tscofig, so we can using

Import Button from "components"

that refs src/components

@VitaminCtea
Copy link
Author

VitaminCtea commented Apr 29, 2020

@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!

@JounQin
Copy link

JounQin commented May 6, 2020

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"
}

@3stacks
Copy link

3stacks commented May 9, 2020

@JounQin if I do what you proposed I get You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file when trying to import another .ts file.

Have you encountered this error?

@JounQin
Copy link

JounQin commented May 9, 2020

@3stacks I didn't get this error.

@fahamidev
Copy link

fahamidev commented Jul 2, 2020

@VitaminCtea
This code worked for me.

stackoverflow.com
Click on me

@cseas
Copy link

cseas commented Jul 11, 2020

create-react-app doesn't support path aliasing and probably won't for the near future.
Reference: #7795 (comment)

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

import { MyComponent } from "src/components"

@nateq314
Copy link

nateq314 commented Jul 20, 2020

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.

@stale
Copy link

stale bot commented Aug 22, 2020

This issue has been automatically marked as stale because it has not had any recent activity. It will be closed in 5 days if no further activity occurs.

@stale
Copy link

stale bot commented Aug 29, 2020

This issue has been automatically closed because it has not had any recent activity. If you have a question or comment, please open a new issue.

@stale stale bot closed this as completed Aug 29, 2020
@avbentem
Copy link

avbentem commented Sep 3, 2020

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. 🥳)

stevenhao added a commit to downforacross/downforacross.com that referenced this issue Dec 26, 2020
stevenhao added a commit to downforacross/downforacross.com that referenced this issue Dec 26, 2020
* wip?

* fixes

* wip

* connect client every time

* pool

* make server use ts

* more

* fix imports

* implicit any true in frontend

* fixes

* refactor fronted src/api

* fix imports

* noimplicitany stuff

* mess around double tsconfig more

* revert PuzzleList

* scaffolding for new puzzle list

* more scaffolding

* ts

* more fixes

* mess around with types

* set up shared path

* tsconfig updates

* tsconfig.base.json

ref: facebook/create-react-app#8909 (comment)

* restore old welcome page

* add localstorage gate for new puzzle list

* restore old upload functionality too

* fix add event
@AleksandrHovhannisyan
Copy link

AleksandrHovhannisyan commented Apr 14, 2021

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

@ZumDeWald
Copy link

ZumDeWald commented Apr 24, 2021

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"
}

Worked perfectly! Thanks for this.

@SimonChaumet
Copy link

SimonChaumet commented Apr 28, 2021

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.

@cseas
Copy link

cseas commented Apr 28, 2021

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.

@DylanCulfogienis
Copy link

DylanCulfogienis commented May 18, 2021

Just ran into this. Hoping to see a resolution some time in the future.

@ramishenouda
Copy link

ramishenouda commented May 19, 2021

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"
}

@zirkelc
Copy link

zirkelc commented May 20, 2021

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".

@zaneclaes
Copy link

zaneclaes commented May 25, 2021

@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.

@mdziekon
Copy link

mdziekon commented May 25, 2021

@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).

@zaneclaes
Copy link

zaneclaes commented May 25, 2021

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.

@AlexandreBrg
Copy link

AlexandreBrg commented Jun 9, 2021

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)

@mdziekon
Copy link

mdziekon commented Jun 9, 2021

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.

@LoveMeWithoutAll
Copy link

LoveMeWithoutAll commented Jun 23, 2021

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.

I got a same issue.

@kishore-s-15
Copy link

kishore-s-15 commented Jul 16, 2021

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.

@hichemfantar
Copy link

hichemfantar commented Jul 24, 2021

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

@jacobedawson
Copy link

jacobedawson commented Aug 5, 2021

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

@AntonioRedondo
Copy link

AntonioRedondo commented Nov 24, 2021

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.

@tiarebalbi
Copy link

tiarebalbi commented Dec 27, 2021

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 :(

@guAnsunyata
Copy link

guAnsunyata commented Dec 29, 2021

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.

@tiarebalbi
Copy link

tiarebalbi commented Dec 29, 2021

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.

@itumoraes
Copy link

itumoraes commented May 30, 2022

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"
}

Worked like a charm! Thanks!

@MrBrN197
Copy link

MrBrN197 commented Jun 4, 2022

I've been struggling to get this to work. Thanks for all the solutions. Although the extends trick doesn't seem to work anymore. 😂almost as if it's actively being prevented.

But seriously, is someone really telling me that no one from the React team is going to explain or acknowledge this in any way at all.

@hichemfantar
Copy link

hichemfantar commented Jun 4, 2022

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

@prestonbrown-me
Copy link

prestonbrown-me commented Sep 16, 2022

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

Was this ever answered? I want to use aliases but it seems like it's discouraged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests