babel.config.js

Babel 配置文件的参考。


Babel 用作 JavaScript 编译器,将现代 JavaScript(ES6+)转换为与移动设备上的 JavaScript 引擎兼容的版本。

¥Babel is used as the JavaScript compiler to transform modern JavaScript (ES6+) into a version compatible with the JavaScript engine on mobile devices.

使用 npx create-expo-app 创建的每个新 Expo 项目都会自动配置 Babel 并使用 babel-preset-expo 作为默认预设。除非你需要自定义 Babel 配置,否则无需创建 babel.config.js 文件。

¥Each new Expo project created using npx create-expo-app configures Babel automatically and uses babel-preset-expo as the default preset. There is no need to create a babel.config.js file unless you need to customize the Babel configuration.

创建 babel.config.js

¥Create babel.config.js

如果你的项目需要自定义 Babel 配置,你需要按照以下步骤在项目中创建 babel.config.js 文件:

¥If your project requires a custom Babel configuration, you need to create the babel.config.js file in your project by following the steps below:

  1. 导航到项目的根目录,在终端内运行以下命令:

    ¥Navigate to the root of your project, run the following command inside a terminal:

Terminal
npx expo customize
  1. 此命令提示生成不同的配置文件。选择 babel.config.js。

    ¥This command prompts generating different config files. Select babel.config.js.

  2. babel.config.js 文件在项目的根目录中创建,默认配置如下所示:

    ¥The babel.config.js file is created in the root of your project with the default configuration as shown below:

babel.config.js
module.exports = function (api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
  };
};
  1. 如果你对 babel.config.js 文件进行了更改,则需要重新启动 Metro 打包程序以应用更改,并使用 Expo CLI 中的 --clear 选项清除 Metro 打包程序缓存:

    ¥If you make a change to the babel.config.js file, you need to restart the Metro bundler to apply the changes and use --clear option from Expo CLI to clear the Metro bundler cache:

Terminal
npx expo start --clear

babel-preset-expo

babel-preset-expo 是 Expo 项目中使用的默认预设。它扩展了默认的 React Native 预设 (@react-native/babel-preset),并增加了对装饰器、树状摇动 Web 库和加载字体图标的支持。

¥babel-preset-expo is the default preset used in Expo projects. It extends the default React Native preset (@react-native/babel-preset) and adds support for decorators, tree-shaking web libraries, and loading font icons.