高阶组件对于CRA的定制

对于CRA的定制

​ 因为我们发现,调用高阶组件的时候采用withCopy(About)代码,但是不够简洁优雅。

import React, { Component } from 'react'
import withCopy from './withCopy'
 class About extends Component {
    render() {
        return (
            <div>
                关于
            </div>
        )
    }
}
export default withCopy(About)

​ 那么我们可以采用装饰器的写法实现调用高阶组件

@WithCopy
class About extends Component {
    render() {
        return (
            <div>
                about -- {this.props.a}
            </div>
        )
    }
}

很不幸,目前的cra是不支持这种写法,我们需要单独进行定制,让其支持这种写法。

Antd中提供了社区解决方案

  1. yarn add @craco/craco

  2. 对脚手架进行轻微的调整

    "scripts": {
    -   "start": "react-scripts start",
    -   "build": "react-scripts build",
    -   "test": "react-scripts test",
    +   "start": "craco start",
    +   "build": "craco build",
    +   "test": "craco test",
    }
  3. yarn start启动项目发现报错了,原因是因为根路径下面缺少 craco.config.js文件

/* craco.config.js */
module.exports = {
  // ...
};
  1. 自定义主题

    index.js文件中:

import 'antd/dist/antd.less';

然后安装 craco-less 并修改 craco.config.js 文件如下。

yarn add craco-less

const CracoLessPlugin = require('craco-less');

module.exports = {
  plugins: [
    {
      plugin: CracoLessPlugin,
      options: {
        lessLoaderOptions: {
          lessOptions: {
            modifyVars: { '@primary-color': 'yellow' },
            javascriptEnabled: true,
          },
        },
      },
    },
  ],
};

后续CRA支持装饰器需要这样配置

yarn add @babel/plugin-proposal-decorators

在craco.config.js文件中新增以下代码即可:

babel: {
   plugins: [["@babel/plugin-proposal-decorators", { legacy: true }]]
},
原文地址:https://www.cnblogs.com/cupid10/p/15617624.html