简体   繁体   中英

Avoid relative path import hell in react-native?

I'm new to react-native coming from vue background, one thing I hate in react is having to use relative path imports in my components, I find myself doing something like:

import HomeScreen from '../../components/screens/HomeScreen'

If my folder structure changes it means I will have to do a search and replace in all of m components using that component, not cool and prone to be a dev hell.

Is it possible to use absolute paths like with node modules, is there a library where I can use aliases or similar, with vue I could import my components in the app.js like Vue.component('home-screen...) and I could use them without having to import.

you can add a package.json file with a name key

{
  "name": "@components"
}

in any folder and metro will recognize it.

You can then import as @components/screens/HomeScreen

If you are using vscode, you can add a jsconfig.json file to your project root to enable import autocomplete.

Here is mine:

{
  "compilerOptions": {
    "baseUrl": "",
    "paths": {
      "@components/*": ["src/components/*"],
      "@helper/*": ["src/helper/*"],
      "@actions/*": ["src/actions/*"],
      "@constants/*": ["src/constants/*"],
      "@primitives": ["src/primitives/index.js"],
      "@graphql": ["src/graphql/index.js"],
      "@services/*": ["src/services/*"],
      "@assets/*": ["assets/*"]
    }
  }
}

The easy method

Add a package.json to important directories with a {"name":"<prefix>"} , similar to a monorepo.

If you are doing this, you can probably also think about making it a full monorepo since there is very little extra work

The incredibly complex method

This method is easier for using things like webpack resolver, etc.

Create a metro.config.js at the root with the following content

module.export = {
    resolver: {
        resolveRequest: (
            context: ResolutionContext,
            moduleName: string,
            platform: string | null
        ) => {
            //...
            return Resolution;
        }
    }
}

Resolution Context

The resolution context is an object that holds attributes of the running resolution, most importantly originModulePath which is the path of the requiring module.

Resolution

The resolution is an object of either:

  1. { type: "empty" } for empty sources
  2. { type: "sourceFile", filePath: string } for JS, JSON, etc. files
  3. { type: "assetFiles", filePaths: string[] } for any other type (eg not metro compilable)

For this method, I would recommend looking at metro-resolver 's types since this method is abysmally documented

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM