如何正确的在 rn 项目中引入 ts 装饰器支持

445 阅读1分钟

如何正确的在 react-native 项目中引入 ts 装饰器支持

module:metro-react-native-babel-preset react-native 脚手架生成的项目是默认不带对装饰器的编译。所以需要引入 babel 插件

yarn add @babel/plugin-proposal-decorators --dev

配置

// babel.config.js
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'babel-plugin-root-import',
      {
        rootPathSuffix: './src/',
        rootPathPrefix: '@/',
      },
    ],
    [
      '@babel/plugin-proposal-decorators',
      {
        legacy: true,
      },
    ],
  ],
};

同时必须 metadata 插件顺序必须在 decorator 之前

然后开启 tsconfig.ts配置

"emitDecoratorMetadata": true,
"experimentalDecorators": true