关于Create React App不支持装饰器的终极无伤解决方案

以前发过一篇解决这个问题的文章,可是对create react app 都是有侵入的。
这里提出一个我以为是最OK的解决方案,一波带走。node

关于Create React App不支持装饰器的解决方案

找到node_modules/react-scripts/config/webpack.config.dev.js文件。
观察其JSX|JS的loader配置。react

// Process JS with Babel.
{
  test: /\.(js|jsx)$/,
  include: paths.appSrc,
  loader: require.resolve('babel-loader'),
  options: {
    // @remove-on-eject-begin
    babelrc: false,
    presets: [require.resolve('babel-preset-react-app')], <===== 注意这里!!
    // @remove-on-eject-end
    // This is a feature of `babel-loader` for webpack (not Babel itself).
    // It enables caching results in ./node_modules/.cache/babel-loader/
    // directory for faster rebuilds.
    cacheDirectory: true,
  },
},复制代码

OK! 咱们找到node_modules/babel-preset-react-app/index.js,而后加入装饰器支持。webpack

/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
'use strict';

const plugins = [
  // 增长装饰器的支持
  require.resolve('babel-plugin-transform-decorators-legacy'), <=== 注意这里!
  // class { handleClick = () => { } }
  require.resolve('babel-plugin-transform-class-properties')
  ....复制代码

记着在对应的package.json下边加入babel-plugin-transform-decorators-legacy。web

而后 cnpm install 再试试使用装饰器,你会发现OK啦。这是目前侵入最小的解决方案。npm

相关文章
相关标签/搜索