React native aliases

quick step

What problem are we solving?

Мery often, when importing files into react native, we get long and inconvenient relative paths such as ../../../. In order to replace them with readable paths like @service/auth. And aliases are needed. Their layout is very precisely related to the syntax and it is necessary not to miss unnecessary slashes and so on. It consists of 2 stages: stage 1 configuration in typescript (if of course you use it).Step 2 is configuring babel itself, which will change them to absolute or relative paths in the final code. That is, you certainly won't have any aliases in the build.
WARNING: if after all steps you get error reset cache  npm start -- --reset-cache


Babel

babel.config.js

module.exports = {
  presets: ['module:@react-native/babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        extensions: [
          '.ios.js',
          '.android.js',
          '.ios.jsx',
          '.android.jsx',
          '.js',
          '.jsx',
          '.json',
          '.ts',
          '.tsx',
        ],
        root: ['.'],
        alias: {
          '@config': './src/config',
          '@styles': './src/styles',
          '@static': './src/static',
          '@services': './src/services',
          '@slices': './src/slices',
        },
      },
    ],
  ],
};

Installing the required package. To make the new babel config work


npm i --save-dev babel-plugin-module-resolver

yarn add --dev babel-plugin-module-resolver

Typescript

tsconfig.json

{


  "extends": "@react-native/typescript-config/tsconfig.json",

  "compilerOptions": {

    "baseUrl": ".",

    "paths": {

      "@static/*": ["src/static/*"],

      "@config/*": ["src/config/*"],

      "@styles/*": ["src/styles/*"],

      "@services/*": ["src/services/*"],

      "@slices/*": ["src/slices/*"],

    }

  },

}

Sign in to leave a comment
Odoo share form to Internet
or share form to public user