在create-react-app脚手架上实现Ant Design按需加载
首先安装babel-plugin-import:
npm i babel-plugin-import -S
然后在.babelrc中添加如下代码:
// .babelrc or babel-loader option { "plugins": [ ["import", { libraryName: "antd", style: "css" }] // `style: true` 会加载 less 文件 ] }
但如果是用的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, }, }
只要把false改成true再重新“npm run start”一下就好了。
后面用的antd组件的地方直接引用就行了,不用再去引样式。
import { Button } from ‘antd‘;
相关推荐
82530995 2020-05-10
游走的豚鼠君 2020-11-10
81417707 2020-10-30
ctg 2020-10-14
小飞侠V 2020-09-25
PncLogon 2020-09-24
jipengx 2020-09-10
颤抖吧腿子 2020-09-04
wwzaqw 2020-09-04
maple00 2020-09-02
青蓝 2020-08-26
罗忠浩 2020-08-16
liduote 2020-08-13
不知道该写啥QAQ 2020-08-02
pengruiyu 2020-08-01
wmd看海 2020-07-27
孝平 2020-07-18
Eduenth 2020-07-05