Reputation: 3553
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.
Upvotes: 6
Views: 4888
Reputation: 2812
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
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;
}
}
}
The resolution context is an object that holds attributes of the running resolution, most importantly originModulePath
which is the path of the requiring module.
The resolution is an object of either:
{ type: "empty" }
for empty sources{ type: "sourceFile", filePath: string }
for JS, JSON, etc. files{ type: "assetFiles", filePaths: string[] }
for any other type (e.g. not metro compilable)For this method, I would recommend looking at
metro-resolver
's types since this method is abysmally documented
Upvotes: 0
Reputation: 1979
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/*"]
}
}
}
Upvotes: 13