在create-react-app脚手架上实现Ant Design按需加载

人生处万类,知识最为贤。这篇文章主要讲述在create-react-app脚手架上实现Ant Design按需加载相关的知识,希望能为你提供帮助。
首先安装babel-plugin-import:

npm i babel-plugin-import -S

在create-react-app脚手架上实现Ant Design按需加载

文章图片
然后在.babelrc中添加如下代码:
// .babelrc or babel-loader option { "plugins": [ ["import", { libraryName: "antd", style: "css" }] // `style: true` 会加载 less 文件 ] }

在create-react-app脚手架上实现Ant Design按需加载

文章图片
但如果是用的create-react-app脚手架的话,初始的根目录里并没有.babelrc文件,那就自己新建一个。
babelrc配置完之后,把项目跑起来发现并不起作用,组件样式并没有加上。
这里其实错的不是我们,也不是antd,而是这个脚手架它默认是不使用.babelrc的,可以在
node_modules/react-scripts/config/webpack.config.js中看到babelrc: false:
{ test: /.(js|mjs|jsx|ts|tsx)$/, include: paths.appSrc, loader: require.resolve(‘babel-loader‘), options: { customize: require.resolve( ‘babel-preset-react-app/webpack-overrides‘ ), // @remove-on-eject-begin babelrc: false, configFile: false, presets: [require.resolve(‘babel-preset-react-app‘)], // Make sure we have a unique cache identifier, erring on the // side of caution. // We remove this when the user ejects because the default // is sane and uses Babel options. Instead of options, we use // the react-scripts and babel-preset-react-app versions. cacheIdentifier: getCacheIdentifier( isEnvProduction ? ‘production‘ : isEnvDevelopment & & ‘development‘, [ ‘babel-plugin-named-asset-import‘, ‘babel-preset-react-app‘, ‘react-dev-utils‘, ‘react-scripts‘, ] ), // @remove-on-eject-end plugins: [ [ require.resolve(‘babel-plugin-named-asset-import‘), { loaderMap: { svg: { ReactComponent: ‘@svgr/webpack?-svgo,+titleProp,+ref![path]‘, }, }, }, ], ], // 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, // See #6846 for context on why cacheCompression is disabled cacheCompression: false, compact: isEnvProduction, }, }

在create-react-app脚手架上实现Ant Design按需加载

文章图片
只要把false改成true再重新“ npm run start” 一下就好了。
【在create-react-app脚手架上实现Ant Design按需加载】后面用的antd组件的地方直接引用就行了,不用再去引样式。
import { Button } from ‘antd‘;

在create-react-app脚手架上实现Ant Design按需加载

文章图片

    推荐阅读