DEV Community

Lê Vũ Huy
Lê Vũ Huy

Posted on

Cài đặt alias trong dự án React Native

Alias là dạng import rút gọn trong các dự án React, giúp chúng ta có code nhìn đẹp hơn. Bạn có thể import dạng @components/Button thay vì ../../components/Button. Các bước để cài đặt alias trong ứng dụng React Native khá đơn giản.

1. Cài đặt

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

2. Setup babel.config.js

Định nghĩa các alias mà bạn sẽ sử dụng trong project, cái này sẽ giúp babel khi thông dịch code ts ra js thì sẽ hiểu dc các import alias.

module.exports = function (api) {
  api.cache(true);
  return {
    presets: ["babel-preset-expo"],
    plugins: [
      [
        "module-resolver",
        {
          alias: {
            utils: "./src/utils",
            screens: "./src/screens",
            components: "./src/components",
            recoilStates: "./src/recoil",
            navigator: "./src/navigator",
          },
        },
      ],
    ],
  };
};
Enter fullscreen mode Exit fullscreen mode

3. Setup tsconfig.json

Định nghĩa lại 1 lần nữa ở bên tsconfig.json, cái này giúp typescript server hiểu được các import alias khi development.

{
  "extends": "expo/tsconfig.base",
  "compilerOptions": {
    "strict": true,
    "baseUrl": "src",
    "paths": {
      "utils/*": [
        "utils/*"
      ],
      "components/*": [
        "components/*"
      ],
      "screens/*": [
        "screens/*"
      ],
      "recoilStates/*": [
        "recoil/*"
      ],
      "navigator/*": [
        "navigator/*"
      ]
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Done 😄

Hãy thử rebuild project của bạn và trải nghiệm, nhớ là mỗi khi thay đổi file babel.config.js thì bạn phải restart metro server nhé (react-native start —reset-cache hoặc expo start -c).

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay