4

I have the following jsconfig.json in the root of my react app:

{
    "compilerOptions": {
      "baseUrl": "./src",
      "paths": {
        "rmv": ["components/rmv/*"]
      }
    }
  }

and there is a helper.jsx file located in ./src/components/rmv folder.

But my attempts to export it directly like that: import Helper from 'rmv/helper' fail with an error:

Failed to compile
Module not found: Can't resolve 'rmv/helper' 

Only import Helper from 'components/rmv/helper' works. Why? PS: I also tried:

"paths": {
        "rmv/*": ["components/rmv/*"]
      }

Does not work either.

Here is the minimum reproducible example: github.com/chapkovski/trouble_with_jsconfig

Specifically these lines: https://github.com/chapkovski/trouble_with_jsconfig/blob/e37c8c216eac0da7c70023f7fba47eea54973176/src/App.js#L4-L5

Philipp Chapkovski
  • 1,949
  • 3
  • 22
  • 43

3 Answers3

15

Paths are currently unavailable in apps made with create-react-app:

https://github.com/facebook/create-react-app/issues/5645

You may want to consider using rescripts to let you modify your configuration in CRA 2+ apps.

Michael Landis
  • 1,074
  • 7
  • 12
  • 1
    Or use [craco](https://www.npmjs.com/package/@craco/craco) (**C**reate **R**eact **A**pp **C**onfiguration **O**verride) – vsync Nov 26 '20 at 16:34
2

The paths need to be relative to the baseUrl. Your baseUrl has a value of ./src which is good. However, your paths listed in the array for rmv/* are NOT relative paths, as they don't start with a relative location (./ or ../).

I would encourage you to try prefixing ./ onto your paths.

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "rmv/*": ["./components/rmv/*"]
    }
  }
}

I found this documentation on the subject: Using webpack aliases

Rob Brander
  • 3,702
  • 1
  • 20
  • 33
  • nope. Here is the minimum reproducible example: https://github.com/chapkovski/trouble_with_jsconfig/ specifically these lines: https://github.com/chapkovski/trouble_with_jsconfig/blob/e37c8c216eac0da7c70023f7fba47eea54973176/src/App.js#L4-L5 – Philipp Chapkovski Feb 21 '20 at 21:48
0

[Eject CRA] You could use webpack alias as alternative solution for the use case.

In webpack.config.js

module.exports = {
  //...
  resolve: {
    alias: {
      rmv: path.resolve(__dirname, 'src/components/rmv/')
    }
  }
};

Now, you could import Helper component as bellow:

import Helper from 'rmv/helper';
DiTaBa
  • 44
  • 2
  • no, it won't work with `react-scripts` without `eject` – Philipp Chapkovski Feb 22 '20 at 16:48
  • I have just updated my answer for correctly. It just support when CRA is ejected. And, paths in jsconfig or tsconfig is still not supported in CRA if you are planning to use this feature in your CRA project you have to wait. – DiTaBa Feb 23 '20 at 02:14