Babel7:装饰器阻止使用静态类属性

时间:2018-10-25 14:43:01

标签: babeljs babel-loader

我对Babel7转换打字稿,装饰器和类属性有疑问。 这是典型的组件,用MobX @observer和我们的@custom装饰器装饰。

@observer
@custom
export class Trends extends React.Component<TrendsProps> {
  .....

  public static readonly METHODS = {
    TOTAL: 'total',
    DIFFERENT: 'different'
  };
  public static readonly defaultState: TrendsStates = {
    method: Trends.METHODS.TOTAL
  };

  .....
}

babel-loader进行编译后,我得到以下目标代码:

// transpiled Trends module code
  return Trends;
}(__WEBPACK_IMPORTED_MODULE_7_react__["Component"]), _class2.METHODS = {
  TOTAL: 'total',
  DIFFERENT: 'different'
}, _class2.defaultState = {
  method: Trends.METHODS.TOTAL
}, _temp)) || _class) || _class);
;

因此,尽管声明静态属性已连接到修饰的类_class2上,但在它们内部却有对Trends类的旧调用,而该调用在当前作用域中根本不存在。 移除装饰器后,所有作品都像一个饰物。 我的babel.config.js

module.exports = api => {
  api.cache(false);

  return {
    presets: [
      [
        '@babel/preset-env',
        {
          targets: {
            browsers: ['last 2 Chrome versions', 'last 2 Safari versions', 'last 2 Firefox versions']
          },
          modules: false,
          forceAllTransforms: true
        }
      ],
      '@babel/preset-react',
      '@babel/preset-typescript',
    ],
    env: {
      test: {
        presets: [['@babel/preset-env'], '@babel/preset-react']
      }
    },
    plugins: [
      ['@babel/plugin-proposal-decorators', { legacy: true }],
      ['@babel/plugin-proposal-class-properties', { loose: true }],
      '@babel/plugin-proposal-object-rest-spread',
      '@babel/plugin-syntax-dynamic-import',
      [
        '@babel/plugin-transform-runtime',
        {
          helpers: true
        }
      ],
      'react-hot-loader/babel'
    ]
  };
};

here解释了问题的根源,但没有babel7的解决方案。 如您所见,我使用了this thread中的建议配置,它确实允许使用装饰器,但是会破坏静态属性。移除@custom装饰器对该问题没有任何影响。

0 个答案:

没有答案