tsconfig.json
or jsconfig.json
:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*":["src/*"]
}
}
}
see https://github.com/facebook/create-react-app/issues/5118
This will help VSCode and other IDE to resolve path in TypeScript & JavaScript.
You may be interested: https://github.com/facebook/create-react-app/issues/5118#issuecomment-434591873
@tanduong if we use yarn-pnp, we have no node_modules
dir.
All of these solutions don't resolve some reasons to just typescript "paths" feature. And without "baseUrl" set to something, paths don't work at all. I really think that baseURL (at least set to .) should be something we can opt into.
I'm having this issue. I have NODE_PATH
set , to make it work w/ TS i need to set paths
to set that I need baseUrl
and here we are.
As a hack/work around, one can set the desired configurations in a different .json
file then use the extends
features of tsconfig.json
. While you do get a warning, it does not override and the settings and proceeds. Using this setting I can test and build without issue (so far)
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"svg/*": ["src/svg/*"],
"components/*": ["src/components/*"]
}
}
}
in tsconfig.json
I have
{
"extends": "./paths.json"
}
One of the side-effects of setting baseUrl: "."
, is that TypeScript now thinks you can import using an absolute path of "src/Foo"
, which may or may not work with the current webpack/jest config. It's unfortunate that we can't use paths
without also being forced to opt into the absolute path from baseUrl
.
@ianschmitz tsconfig-paths-webpack-plugin can works with current webpack config. We can use tslint to show warn of 「using an absolute path of "src/Foo"」
It just works with [email protected] and react-app-rewire-typescript-babel-preset@3
I waste half day on this. Now I decide downgrade.
We have our own version of react-scripts
and customise this for our needs.
One solution I think could work is to allow it to be set whenever NODE_PATH is set to src
, for less confusion (note, I don't use the @
-style).
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["src/*"]
}
}
}
As a hack/work around, one can set the desired configurations in a different
.json
file then use theextends
features oftsconfig.json
. While you do get a warning, it does not override and the settings and proceeds. Using this setting I can test and build without issue (so far){ "compilerOptions": { "baseUrl": ".", "paths": { "svg/*": ["src/svg/*"], "components/*": ["src/components/*"] } } }
in
tsconfig.json
I have{ "extends": "./paths.json" }
It seems not work at [email protected]
@babakness I would name that paths.json
file tsconfig.paths.json
so that vscode provides Intellisense for the file.
Also, why not just "baseUrl": "./src"
? Are you importing files outside of ./src
? Just trying to understand the motifivation, because managing all the folder names within src
is not ideal.
I've tried extending tsconfig.json but it's still unable to resolve, I'm using [email protected]
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.
What is the current recommendation for getting absolute paths to work? It would be great if it worked with TypeScript's built in way of doing this.
I am trying to use baseUrl
and paths
but CRA automatically removes those settings from my tsconfig.json
completely disabling the use of them which is highly frustrating.
@ChristianIvicevic I had the same issue. Once I realized that's not a supported path, I 🤷♂️
This issue is disappointing, since I want to avoid weird relative paths, especially something like ../../../components/Foo/Bar
. On the other hand I'd really prefer not to eject at all since I don't need a full blown customization of the default configuration. It just bothers me how opinionated CRA is while still being so useful for small pet projects at the very same time.
It is frustrating. It doesn't make sense that anyone would have to eject for something so small like this.
Some hack ideas I have is to configure the file system to prevent overriding the file by CRA and to try the new TypeScript 3.2 feature where you can extend
from an NPM package.
https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#tsconfigjson-inheritance-via-nodejs-packages
I don't have time to hack it right now but honestly one reason I've not upgraded CRA2 since the extend
hack above was patched.
CRA2 should at least allow us to do what we want at "our own risk".
The more important question is _why_ is CRA changing this file? What's the underlying problem or concern? I'd love to know, because perhaps someone can come up with a better solution.
Reasoning is here: https://github.com/facebook/create-react-app/issues/5585#issuecomment-433900655
I think users should be allowed to change config even if it is not supported at their own risk.
Some hack ideas I have is to configure the file system to prevent overriding the file by CRA and to try the new TypeScript 3.2 feature where you can
extend
from an NPM package.
I actually attempted this as well as described here: https://github.com/facebook/create-react-app/issues/5645#issuecomment-435201019
Unfortunately CRA had a meltdown and basically ignores the settings.
@ChristianIvicevic you tried specifically through NPM? So the config lives in node_modules. I believe at the time of the comment. That feature was not released yet.
@babakness I tried extending an external tsconfig (not in node_modules though) and the react-scripts noticed something odd, attempted to remove baseUrl and paths, but failed, messed with the formatting, but luckily left the extended file that only contains baseUrl and paths. Unfortunately the application had an error at this point since paths could not be resolved. Likely an issue due to babel not being able to properly resolve the actual paths.
Like most people I've followed this workaround (thanks for it btw), however with the latest react-script
it keeps modifying and checking out my tsconfig.json
, which is quite frustrating. All I wanted to do is setup the baseUrl
and paths
property so that it aligns with my NODE_PATH=src/
settings in order to get intellisense and typescript compiler support with imports. Not doing any breaking changes!
Anyway, this comment led me to an alternative solution, using the following steps:
postinstall
script. Instructions available on the patch-package repo.verifyTypeScriptSetup.js
from node_modules\react-scripts\scripts\utils
by removing this section.npx patch-package react-scripts
. This will creates a patches
folder with a .patch
file corresponding to the change made inside verifyTypeScriptSetup.js
.patch-package
will apply the patch whenever you run npm install
or npm ci
.
Few things to keep in mind with this workaround:
react-scripts
changes the way it enforces the baseUrl
restriction, you'll need to carry out the above steps to patch whatever new method is used.react-scripts
starts supporting baseUrl
, remove this workaround and the patch and just start using react-scripts
as normal.No an ideal situation to be in, but it'll do for the time being until better support is provided. Also it means I don't have to fork the repo.
Hope it helps.
@IIFE curious, what instead of extends
from a local file, we extend from node_modules
using TypeScript 3.2 new feature
https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#tsconfigjson-inheritance-via-nodejs-packages
Have you tried this?
@IIFE curious, what instead of
extends
from a local file, we extend fromnode_modules
using TypeScript 3.2 new featurehttps://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#tsconfigjson-inheritance-via-nodejs-packages
Have you tried this?
I haven't tried extending from node_modules. I might give it a try in a test project. However, I don't think the behaviour will be any different. My understanding is that node_modules
inheritance is just simply allowing a package path to be specified for extends
, the outcome is probably just the same as extending from a local path.
I thought tsconfig.json
is TS-specific which is why I initially didn't want to support this particular way of configuring it, and preferred alternatives (https://github.com/facebook/create-react-app/issues/5692 and https://github.com/facebook/create-react-app/issues/5118). But it seems like VS Code also respects jconfig.json
which also supports a paths
option.
My proposal: Let’s read paths
configuration from jsconfig.json
/ tsconfig.json
, and use it everywhere (including for Webpack and Jest). This could also supersede the NODE_PATH
solution for JS users.
Any objections to this?
@gaearon Like that idea! I just created a PR to kickstart NODE_PATH
support in TS: https://github.com/facebook/create-react-app/pull/6116 but happy to change that to support a tsconfig.json
/jsconfig.json
convention. That immediately solves one of the issues I encountered with letting vscode understand the NODE_PATH
magic happening behind the scenes.
Thanks for jumping on this!
I'd be happy to deemphasize NODE_PATH
support if jsconfig.json
/ tsconfig.json
solve this better. Does its configuration cover all use cases for NODE_PATH
?
Can someone explain to me what baseUrl
is for? All examples I can find are using '.'
.
I think if these Use cases are supported, it will be fine:
{
"compilerOptions": {
"baseUrl": "src"
}
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*":["src/*"]
}
}
}
As far as I understand react-scripts
it only uses NODE_PATH
to match Node's resolving mechanism in Webpack. So we should be able to just replace that with a path from jsconfig.json
/ tsconfig.json
.
But would be good to have @Timer's confirmation if I don't overlook any other use cases for NODE_PATH
.
Do we know that every valid baseUrl
/ paths
combination is "translateable" into Webpack/Jest terms without losing information?
Well, in theory you could set baseUrl
to .
and your editor would not warn you if you import something like src/components/button
while from the point of CRA we don't want people to set up an absolute path outside of the src
directory.
I think the best way to prevent people from doing this is to fail the build and throw a warning saying we do not allow baseUrl
/paths
outside of the src
directory.
We could also support it but without passing these files through Babel.
Won't that confuse people that their files don't get transpiled? I have already seen a few issues of people trying to put JS files outside of the src
directory for various reasons.
We auto-generate the config, so a quick solution would be to force tsconfig.json
to match NODE_PATH
if it's set. This is a quick win that will please many, but not all users.
We auto-generate the config, so a quick solution would be to force
tsconfig.json
to matchNODE_PATH
if it's set. This is a quick win that will please many, but not all users.
I understand NODE_PATH supports multiple values with a delimiter. src,whatever,.. and I think jsconfig / tsconfig baseUrl can only be one.
https://github.com/facebook/create-react-app/blob/c8c3e48abd4bb93febf2c94b1b5fdb4f8738540e/packages/react-scripts/config/env.js#L62
I think, baseUrl only will make sense with value 'src', since the appSrc is always 'src'
https://github.com/facebook/create-react-app/blob/c8c3e48abd4bb93febf2c94b1b5fdb4f8738540e/packages/react-scripts/config/paths.js#L107
I think it's reasonable to only allow src
as baseUrl
in the first implementation and see if other needs arise.
Would that still allow aliasing src
to @
?
@gaearon it would. I have updated my PR (#6116) with a way to read the baseUrl from these config files but only allow src
as a value.
Doesn't seem so difficult to add support for the @
alias as well. However how much control do we want to give the user? As the paths
are quite flexible on their own. Do we want to restrict it to only @
to src
at this stage?
I don't think we need to support the @
alias in this effort, as it's more of a convention than a feature.
Also, @JulianIsrael, baseUrl
is a single value, but paths
supports multiple. My opinion is that we should try to map this to NODE_PATH
for consistency.
Well, the NODE_PATH
convention never really took off. As far as I know, there's no editor supporting it and many tools don't respect it either. Given the huge amount of people in the JS community using vscode
I think it's a good choice to go with this jsconfig.json
/tsconfig.json
convention. If CRA would support that I think that would tremendously help with setting a good convention within the community.
I'm totally in favor of supporting only the baseUrl
option, but I know a lot of people rather have some sort of prefix to make a distinction between their own code and vendor code. So I'll leave it to @gaearon for which direction we want to take here. Happy to implement it either way!
Agreed @rovansteen, if NODE_PATH
is we could avoid NODE_PATH
altogether, that would be ideal - what I want to avoid is a world where we have both in place.
@rovansteen We tend to use ~/
as the prefix but it's trivial for us to change it to @
or something too. In terms of a big deal vs. little deal, it's not a big deal to not have a prefix but like you said, it denotes _our_ code vs. vendor code.
@gaearon You had asked what baseUrl
is used for in TS. Can try to help there.
The official description is:
Base directory to resolve non-relative module names. See Module Resolution documentation for more details.
From that other reference:
http://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url
Setting baseUrl informs the compiler where to find modules. All module imports with non-relative names are assumed to be relative to the baseUrl.
Value of baseUrl is determined as either:
- value of baseUrl command line argument (if given path is relative, it is computed based on current directory)
- value of baseUrl property in ‘tsconfig.json’ (if given path is relative, it is computed based on the location of ‘tsconfig.json’)
Note that relative module imports are not impacted by setting the baseUrl, as they are always resolved relative to their importing files.You can find more documentation on baseUrl in RequireJS and SystemJS documentation.
The phrase all non-relative imports is important. Setting baseUrl
to ./src
actually will have TS search for regular node_modules
packages relative to that path.
Meaning this:
import React from 'react'
Won't work because it's searching from ./src/*
. That's why you see .
used everywhere, as it's relative to the tsconfig.json
which is typically next to node_modules
.
Note: I'm saying it doesn't work but the case I'm using, I'm doing
import { ExecutionResult } from "graphql"
and I have asrc/graphql.ts
file, and it uses that instead of the node module, seen here:
You can get the above to work by doing:
{
"baseUrl": "./src",
"paths": {
react: ["../node_modules/react"]
}
}
But that's probably not what you'd like.
Someone correct me if I'm wrong but I think that helps explain its purpose.
Also, FWIW, I'd love zero restrictions on what we can add to paths
since you can do nice aliasing with it. You could force @/
or ~/
or whatever in there by default, but if we add our own paths, I wouldn't want them overwritten/blown away.
@kamranayub TypeScript will mimic node resolution by moving upwards in the directory tree and look for node_modules
folder if it can't find the module. So if you set your baseUrl
to src
it will still look for React in ../node_modules/react
after it wasn't able to find it in src
.
@rovansteen if it wasn't able to find it; but in my example above, I have a file (module) graphql.ts
and it chose that, instead of the npm package graphql
like it was doing properly before (using baseUrl: "."
).
@kamranayub if you have the @types/graphql installed, that shouldn't be happening. Apparently it would prefer ts modules first than js on its resolution.
Using the "extends": "./tsconfig.extend.json"
and the "baseUrl": "./src"
solves the compilation issue (currently on "react-scripts": "2.1.3"
).
However the build fails with Cannot find module 'xyz' from ...
during the test phase. I had a similar issue on a setup with Webpack, it was solved by updating the moduleNameMapper
on the jest.config.js
.
@mrmckeb, @gaearon What is the current status / is it possible to help?
@marc-ed-raffalli this is officially not supported yet. See #6116 for the progress for official support for this in TypeScript.
As far as I can tell only actual import alias are discussed here as a use case i.e. telling cra to emit an import alias via tsconfig.json paths
.
However this is not the primary concern of paths
. This option does not change how tsc
emits import paths. This is purely for the typechecker to know where to look for types. E.g. I'm using react-redux@3
and @types/react-redux
. To tell the type checker what types I'm using I would have to add the following to my tsconfig:
"paths": {
"react-redux": [ "react-redux/v3" ]
},
This would break at runtime if create-react-app
would actually change the import paths in the emitted code.
Source: Microsoft/TypeScript#10866
My 2cts after having played with this for a while:
For a solution to absolute paths without any customization, you can use the following solution (tested with [email protected]
, [email protected]
).
.env
file:NODE_PATH=./
tsconfig.paths.json
file:{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"src/*": ["*"]
}
}
}
tsconfig.json
."extends": "./tsconfig.paths.json"
Both compilation and intellisense should now work with absolute import support using the src/
prefix 🎉 (eg. import Counter from 'src/components/Counter';
)
You can even reuse the exact same setup (without even needing the extends hack) for non-typescript projects with a jsconfig.json
file.
I quite like the src/
prefix convention which is perfectly explicit (Principle of Least Surprise) vs a more cryptic @/
or ~/
, tilde is also commonly aliased tonode_modules/
in the scss world so I think it should be avoided.
And the bonus point for src/
is that it easily works outside the box thanks to the NODE_PATH
env var without any extra webpack tweaks. Also works with jest tests (but if you want to store them inside the root test
directory, you'll have to add "test"
to the "include"
array in the tsconfig.json
(won't be overwritten).
Finally if you start working on mono-repos of CRA's (I've been doing that lately to leverage a shared storybook-based components "library" across multiple apps), you'll encounter errors when cross referencing files that all uses the same absolute convention, I've built a babel plugin to address that, might be useful.
@mgcrea your solution does work!
The only limitation I found is that vscode does not know how to resolve missing imports this way. It won't build the the right path.
Using only:
{
"compilerOptions": {
"baseUrl": "."
}
}
seems sufficient to use src/
. I then limit import outside of src
using TS Lint.
@mgcrea Thank you for the solution!
My only gripe with it, is that CRA still says that the baseUrl and paths should not be set (and tries to unset them in vain)
Have you found a solution for it? or do you simply ignore the error?
I've just tried the above solution with [email protected]
and it didn't work.
The intellisense doesn't complain but if I try to open the project in browser it fails to resolve my module :slightly_frowning_face:
@dorshinar I just simply ignore the error, it will probably go away when it becomes officially supported.
@mikheevm Just re-tried from scratch my solution with [email protected]
and encountered no issues.
@joelbourbon In my case vscode does properly resolve missing imports too:
@mgcrea Looks like this approach doesn't work well with the new TS speed improvement (react-scripts 2.1.8). It doesn't type-check dependent modules.
Scenario:
// src/index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import Test from 'src/shared/Test';
ReactDOM.render(
<Test a={123} />,
document.getElementById('root')
);
// src/shared/Test.tsx
import React from 'react';
type Props = {
a: number;
}
const Test = (props: Props) => <div>a={props.a}</div>;
export default Test;
So far so good, it all compiles, and the module path src/shared/Test
resolves well.
Now the funny part. I do some refactoring for the Test component - rename the prop a
to b
.
Recompilation happens, but no error is emitted from TS type check - apparently the type checking for src/index.tsx
file never ran.
I need to modify the file src/index.tsx
in any way (e.g. add an extra empty line somewhere) in order to trigger type checking for this file - only then the type error ("Property 'a' does not exist on type 'IntrinsicAttributes & Props'") is emitted.
This is essentially a blocker for me. In the meantime I have to downgrading to react-scripts 2.1.3 - in order to be able to use absolute import paths (configured via tsconfig.paths.json).
Do you have any workaround for that @mgcrea?
@mikheevm
I've just tried the above solution with
[email protected]
and it didn't work.
The intellisense doesn't complain but if I try to open the project in browser it fails to resolve my module 🙁
I had that issue. In my case it was caused by a very weird factor: I had a custom NODE_PATH environment variable defined in my bash profile. Somehow it didn't play well with the setup, and even overriding it in .env file wouldn't work.
My 2cts after having played with this for a while:
For a solution to absolute paths without any customization, you can use the following solution (tested with
[email protected]
,[email protected]
).
- Add a
.env
file:NODE_PATH=./
- Add a
tsconfig.paths.json
file:{ "compilerOptions": { "baseUrl": "src", "paths": { "src/*": ["*"] } } }
- Add the following line at the end of the generated
tsconfig.json
."extends": "./tsconfig.paths.json"
Both compilation and intellisense should now work with absolute import support using the
src/
prefix 🎉 (eg.import Counter from 'src/components/Counter';
)You can even reuse the exact same setup (without even needing the extends hack) for non-typescript projects with a
jsconfig.json
file.I quite like the
src/
prefix convention which is perfectly explicit (Principle of Least Surprise) vs a more cryptic@/
or~/
, tilde is also commonly aliased tonode_modules/
in the scss world so I think it should be avoided.And the bonus point for
src/
is that it easily works outside the box thanks to theNODE_PATH
env var without any extra webpack tweaks. Also works with jest tests (but if you want to store them inside the roottest
directory, you'll have to add"test"
to the"include"
array in thetsconfig.json
(won't be overwritten).Finally if you start working on mono-repos of CRA's (I've been doing that lately to leverage a shared storybook-based components "library" across multiple apps), you'll encounter errors when cross referencing files that all uses the same absolute convention, I've built a babel plugin to address that, might be useful.
I seem to have an issue with this where my zsh-shell in iTerm2 can't compile a project with this construction due to modules not being found when using src/--
. But it does compile (as expected) when running zsh within Visual Studio Code's terminal, where both are running the same node & npm version. 🤡
baseUrl
is now supported in tsconfig.json
and jsconfig.json
. paths
is still yet to come. Check out #6475 and install our alpha release if you want to try it out!
@rovansteen Any plan to work on path aliases as initially planned in #6116 ?
@rovansteen Including paths in an upcoming patch would be very very nice.
Out of interest why do some authors choose to use @
as a prefix for aliased imports - I thought that might be confused with using scoped packages from node_modules?
I don't understand either. It makes much more sense to use "src/..." as that's the actual name of the folder
@delaaxe, I actually agree with you entirely. That type of aliasing doesn't make sense to me, as no clearer than not aliasing with an @
now that we have scoped modules.
@mikheevm
I've just tried the above solution with
[email protected]
and it didn't work.
The intellisense doesn't complain but if I try to open the project in browser it fails to resolve my module 🙁I had that issue. In my case it was caused by a very weird factor: I had a custom NODE_PATH environment variable defined in my bash profile. Somehow it didn't play well with the setup, and even overriding it in .env file wouldn't work.
This works for me
My 2cts after having played with this for a while:
For a solution to absolute paths without any customization, you can use the following solution (tested with
[email protected]
,[email protected]
).
- Add a
.env
file:NODE_PATH=./
- Add a
tsconfig.paths.json
file:{ "compilerOptions": { "baseUrl": "src", "paths": { "src/*": ["*"] } } }
- Add the following line at the end of the generated
tsconfig.json
."extends": "./tsconfig.paths.json"
Both compilation and intellisense should now work with absolute import support using the
src/
prefix 🎉 (eg.import Counter from 'src/components/Counter';
)You can even reuse the exact same setup (without even needing the extends hack) for non-typescript projects with a
jsconfig.json
file.I quite like the
src/
prefix convention which is perfectly explicit (Principle of Least Surprise) vs a more cryptic@/
or~/
, tilde is also commonly aliased tonode_modules/
in the scss world so I think it should be avoided.And the bonus point for
src/
is that it easily works outside the box thanks to theNODE_PATH
env var without any extra webpack tweaks. Also works with jest tests (but if you want to store them inside the roottest
directory, you'll have to add"test"
to the"include"
array in thetsconfig.json
(won't be overwritten).Finally if you start working on mono-repos of CRA's (I've been doing that lately to leverage a shared storybook-based components "library" across multiple apps), you'll encounter errors when cross referencing files that all uses the same absolute convention, I've built a babel plugin to address that, might be useful.
Unfortunately does not work anymore with [email protected]
, reproduced here
@mytee306 indeed I was disappointed to notice that they broke absolute paths with src/
prefix (probably with #6656). Haven't found a simple workaround for now, but didn't really have time to dig in. I guess we might have to wait for aliases support (but could be a long time). For now I'm staying on the 2.x branch. Will try to revisit later.
@mytee306 That trick still works for me on 3.0.1 without rewired. I had to set NODE_PATH in package.json so it doesn't get overridden by system variables
@delaaxe I've create a branch which does not use react-app-rewired
and I've even set the env
variable inline, however the compiler still attempts to resolve the package in <project root>/src
@mytee306 Got it working by changing
TS options to :
"baseUrl": ".",
"paths": {
"src/*": ["src/*"],
"lib/*": ["lib/*"]
}
Now in index.tsx I can use real absolute paths :
import Foo from "src/path/to/Foo";
Same thing for lib
Has anyone gotten this to work without TS? I saw the deprecation warning about no longer supporting NODE_PATH
in .env
, so I've tried adding a bunch of the above suggestions to a jsconfig.json
file, such as:
{
"compilerOptions": {
"baseUrl": "src"
}
}
(along with different "paths" like "src/*": ["*"]
), but I can't seem to get it to work (on react-scripts
3.0.1). Still getting ./src/index.js Module not found: Can't resolve 'src/containers/App'
.
@delaaxe Typescript recognizes the type signature and VSCode references also work out of the box. The issue pops up when you run the start script.
Nothing works for paths
in tsconfig
as of version 3.0.1
. Which makes yarn link
ed packages impossible to work with...
And here I though I can use lerna wit ts packages and just set up paths to have HMR :D
Are there any improvements to this?
As a hack/work around, one can set the desired configurations in a different
.json
file then use theextends
features oftsconfig.json
. While you do get a warning, it does not override and the settings and proceeds. Using this setting I can test and build without issue (so far){ "compilerOptions": { "baseUrl": ".", "paths": { "svg/*": ["src/svg/*"], "components/*": ["src/components/*"] } } }
in
tsconfig.json
I have{ "extends": "./paths.json" }
If it doesn't work and you are using monorepo like me.
U can try this hack: (it solved my problem perfectly)
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@packages/*": ["../packages/*"]
}
}
}
Hope to solve your problem.
If you're not using TypeScript, set jsconfig.json
in the root directory to
{
"compilerOptions": {
"baseUrl": "src"
}
}
, then update your imports to remove src
.
Why can't people simply include "src" in absolute imports?
Easier to understand, makes it much more obvious which files are internal and which are external deps. Explicit better than implicit.
I had to use this in jsconfig.json file in my project root for vscode to serve my application to localhost. Not having 'paths' defined did not work. Also having an .env file in addition to jsconfig.json also did not work. I had to delete the .env file.
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@/*": [
"src/*"
]
}
}
}
For those of you still having problems with absolute paths and nested folders path
here is what it's working for me.
Basically the baseUrl and the include with src/**/ if you just src or src/ it will not reach the nested folders.
Feel free to use as a template and modify to your needs
{
"compilerOptions": {
"baseUrl": "src",
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"strictNullChecks": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"noUnusedLocals": true,
"allowJs": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"rootDir": "src",
"resolveJsonModule": true,
"noEmit": true,
"jsx": "preserve",
"skipLibCheck": true,
"isolatedModules": true,
"typeRoots": [
"./src/types",
"./node_modules/@types"
],
"outDir": "build/dist",
"sourceMap": true,
"suppressImplicitAnyIndexErrors": true
},
"include": [
"src/**/*"
],
"exclude": [
"./src/types",
"node_modules"
]
}
Has anyone gotten typescript references to work?
Using the recommended tsconfig.paths.json
hack:
{
"compilerOptions": {
"baseUrl": "../",
"paths": {
"@bubbles/*": ["./*/src"],
"*": ["./types/external/*"]
}
},
"include": [
"src"
],
"references": [
{
"path": "../types"
},
{
"path": "../serverless-data-api"
}
]
}
I'm getting this error: File '/.../bubbles/packages/serverless-data-api/src/index.ts' is not under 'rootDir' '/.../bubbles/packages/web-ui/src'. 'rootDir' is expected to contain all source files.
References work fine for non-CRA packages but not for a CRA package. Strangely enough, CRA starts compiling when removing both references
completely, which is weird because I do depend on these references.
Why can't people simply include "src" in absolute imports?
Easier to understand, makes it much more obvious which files are internal and which are external deps. Explicit better than implicit.
Because, for example, you have a main root package1 and a nested package2 (using yarn workspaces for instance)
baseUrl: 'src'
import something2 from "components/something2"
import something from '@package2/src/components/something1'
It would be much easier to have "paths" in both packages and import everything using the aliases provided there. It would be:
import something2 from "@package2/components/something2"
import something1 from "@package2/components/something1"
Have tried many of the solutions for TS posted here and on #5118, and none of them seems to work as of now (using latest version of CRA).
The only thing that seems to work is to create an @ package on node_modules and then link it using yarn, which does not sound like an optimal solution.
I tried to use absolute import as describe here : https://create-react-app.dev/docs/importing-a-component#absolute-imports (using jsconfig.json
)
but i get conflict between one folder of the project and node_modules when i try to import through index.js
i think add paths
in compilerOptions can solve this
@LoiKos please file a new issue and fill in the issue template.
@LoiKos please file a new issue and fill in the issue template.
Most helpful comment
As a hack/work around, one can set the desired configurations in a different
.json
file then use theextends
features oftsconfig.json
. While you do get a warning, it does not override and the settings and proceeds. Using this setting I can test and build without issue (so far)in
tsconfig.json
I have