React中使用antd 4.x CSS文件按需加载 babel-plugin-import

React中使用antd 4.x后在网上没搜到CSS按需加载的教程,自己摸索了一番,踩了一些坑,简单记录一下。


2021-7-8更新:

craco社区是有相关插件来完成按需加载功能的,自己之前没注意…
在这里插入图片描述
craco传送门:https://github.com/gsoft-inc/craco
在这里插入图片描述
craco-antd传送门:https://github.com/DocSpring/craco-antd


  • 在antd 4.x后,使用 craco对 create-react-app 进行自定义配置。 craco相关配置看官网

  • 使用babel-plugin-importbabel-plugin-import是一个用于按需加载组件代码和样式的 babel 插件

    1. 安装:$ yarn add babel-plugin-import
    2. 配置:在craco.config.js中配置如下:
      module.exports = {
      		            babel: {
      		                plugins: [['import', {
      		                    libraryName: 'antd',
      		                    libraryDirectory: 'es',
      		                    style: 'css',
      		                }]],
      		            },
      		        };
      
  • 踩坑:
    不要使用.babelrc文件,原因看这
    曾尝试引入craco社区维护的相关插件来解决.babelrc问题,最终以失败告终
    image

  • 还是多看官方的配置文档有用。
    babel-plugin-import
    craco

  • 补充:在网上看见了一个其他教程,未测试是否可用
    https://www.cnblogs.com/leyi/p/10985913.html


版权声明:本文为leejieleejie原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。