關於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

相關文章
相關標籤/搜索