create-react-app 踩坑记

1. 引入antd 按需加载

我是npm run eject后的进行引入antd
首先需要安装 babel-plugin-import

create-react-app 生成项目后,在package.json下面会有下面的配置:

 "babel": {
     "presets": ["react-app"]
 }

在上面的基础上修改

  "babel": {
    "presets": ["react-app"],
    "plugins": [
      [
        "import",
        {
          "libraryName": "antd",
          "style": "css"
        }
      ]
    ]
  },

在react里直接写,就可以了

import { Button } from "antd";

按理说新建.babelrc

{
  "presets": ["react-app"],
  "plugins": [
    [
      "import",
      {
        "libraryName": "antd",
        "style": "css"
      }
    ]
  ]
}

这样也可以达到目的的,但是样式出不来

还有一种方式是修改webpack配置,但是记得在dev和prod都要修改

       {
            test: /\.(js|jsx|mjs)$/,
            include: paths.appSrc,
            loader: require.resolve("babel-loader"),
            options: {
              plugins: [
                //  css
                ["import", { libraryName: "antd", style: "css" }]
                //  less or sass
                // ["import", { libraryName: "antd", style: true }]
              ],

              // 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
            }
          },

2. 打印编译时间

  1. yarn build --profile --json
    使用npm run build --profile --json无效
    Support for '--profile' option for webpack from react-scripts build
  2. time npm run build
    Add a compile time to webpack dev server and react-scripts #2576

webpack文档:

Hints from build stats

There is an analyse tool which can perform a detailed analysis and provide useful information on how to optimize your build size and performance.

You can generate the required JSON file by running webpack --profile --json > stats.json

build performance

  1. antd Upload 3.x 限制上传文件个数

  • 对于没有使用getFieldDecorator包裹的Upload 直接用state进行受控
    完全控制的上传列表
  • 对于使用getFieldDecorator包裹的Upload
        
          {getFieldDecorator('upload', {
            valuePropName: 'fileList',
            getValueFromEvent: this.normFile,
          })(
            
              
            ,
          )}
        

normFile 函数

  normFile = e => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList.slice(-1);//截取最后的文件
  };

你可能感兴趣的:(create-react-app 踩坑记)