DEV Community

timeturnback
timeturnback

Posted on

How to setup static directory for React / React Native ( @app )

Sometime you find out that the relative directory stress you up with a thoundsand character of path . this post is for you

import SomeThing from "../../../../../../../../components/Something";
Enter fullscreen mode Exit fullscreen mode

static directory example

Frist . You will need some package

yarn add -D babel-plugin-module-resolver
Enter fullscreen mode Exit fullscreen mode

Then . The .bablerc ( or babel.config.js )

module.exports = function (api) {
  api.cache(true);
  return {
    presets: ["babel-preset-expo"],
    plugins: [   // this plugins part 
      [
        'module-resolver',
        {
          alias: {
            '@app': '.' // if app files is inside "app/" folder, replace with "./app"
          }
        }
      ]
    ]
  };
};
Enter fullscreen mode Exit fullscreen mode

Tips : maybe , when you copy this file from some template project , it will not replace a current default file and become babel copy.config.js and it will not work . Double check this .

OK , you can make a clean run and this will work .

Ok . It's actually can work now . But . If you need VS Code to help you redirect to the directory of file . you will need those 2 thing .

.vscode/setting.json

{
  "path-autocomplete.pathMappings": {
    "@app": "${workspace}" // alias similar to defined in .babelrc
  }
}
Enter fullscreen mode Exit fullscreen mode

jsconfig.json

{
    "compilerOptions": {
        "allowJs": true,
        "allowSyntheticDefaultImports": true,
        "experimentalDecorators": true,
        "jsx": "react",
        "module": "es6",
        "moduleResolution": "node",
        "baseUrl": ".",
        "paths": {
            "@app/*" : ["./*"] // alias similar to defined in .babelrc
        },
        "sourceMap": true,
        "target": "ES6"
    },
    "exclude": [
        "node_modules"
    ]
}
Enter fullscreen mode Exit fullscreen mode

That should work

One last things . If somehow your metro didn't found the directory . You make need to perform a clean start :

expo start -c // expo 
npx react-native start --reset-cache // react native base
Enter fullscreen mode Exit fullscreen mode

Top comments (0)