4

In the past, we had a problem importing files from the local working directory when using React Native. Then we found a way from React Native Github: https://github.com/facebook/react-native/issues/3099#issuecomment-221815006.

So for example, we had the folder structure like this:

src
- core/
- config/
  - package.json
  - file1.js

- index.js
- package.json
- package-lock.json

And we could declare our config/ folder as a custom npm module by setting this in config/package.json:

{
  "name": "@config"
}

Then we could import the file1 from anywhere using:

import { something } from "@config/file1";

But the problem is that, in this way, VScode lost the ability to auto-complete and intellisense the import path import from "@somewhere", and VScode could not detect the actual content of the imported variables like something above from file1

So is there a way to configure our React Native project such that VScode could intellisense and detect this kind of custom import?

Jonathan
  • 581
  • 1
  • 6
  • 15

3 Answers3

3

Here's a simple solution I've found from the VS docs here

Declare a jsconfig.json file at the same level as your index.js file. Declare all the custom modules in the paths object.

A config file I've used for one of my projects:

{
    "compilerOptions": {
        "target": "es6",
        "baseUrl": "./",
        "paths": {
            "@assets/*": [
                "./src/assets/*"
            ],
            "@config/*": [
                "./src/config/*"
            ],
            "@screens/*": [
                "./src/screens/*"
            ],
            "@library/*": [
                "./src/library/*"
            ],
        }
    }
}
l0h1t
  • 363
  • 2
  • 10
  • Thanks! This method works well! But I think we should gradually migrate from using custom ```package.json``` to ```import "src/"```. Create-react-app 3.x ships default ```jsconfig.json``` with ```baseUrl: src```. With current ```package.json``` way we have to define too many custom mapping in ```paths```. – Jonathan Aug 08 '19 at 07:05
0

Answear by Lohit is correct, but please note that you might want to use ** to match all paths recursively, I think it's safer to do that:

{
  "compilerOptions": {
      "baseUrl": "./",
      "paths": {
          "lib/**": [
              "./lib/**"
          ]
      }
  }
}

This way when you can do import ... from "lib/nested/path/will/work"

You can check the difference between * and ** here: https://stackoverflow.com/a/66744400/5155607

mykhailoklym94
  • 577
  • 6
  • 13
0

They just fixed it back in version 1.60.0. Rejoice!

  • Please provide additional details in your answer. As it's currently written, it's hard to understand your solution. – Community Sep 02 '21 at 19:27
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – JW Geertsma Sep 03 '21 at 12:38