實現Ant Design按需加載


下載antd:

npm i antd -S

安裝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的,它使用的是package.json中的babel配置和內部配置。

所以我們要將腳手架的內部配置項暴露出來進行修改,使用 npm run eject這個命令來暴露配置,運行npm run eject之后,項目根目錄會生成config文件夾。

找到config/webpack.config.js文件,將babelrc:false改為true,意思是啟用.babelrc的配置:

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

還沒有完,此時如果運行項目,瀏覽器還會報錯,為什么會報錯呢?因為上面一步開啟了使用.babelrc文件,但是.babelrc的配置不正確,我們需要修改(為什么不正確呢?因為creat-react-app有一些默認的babel配置放到了package.json中)

此時將package.json中的babel下面的 “presets”: [ “react-app” ] 配置到 .babelrc中,並將package.json中的babel刪除掉,如圖:

總結一下,create-react-app的腳手架使用anted的css按需加載,由於此腳手架默認不支持使用.babelrc文件,所以需要將其配置暴露出來,需要用到npm run eject 命令,暴露配置文件后需要在config/webpack.config.js中開啟使用.babelrc文件的功能,開啟后配置.babelrc。配置的時候需要注意一點,將package.json中的babel配置剪貼到.babelrc中。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM