create-react-app按需配置antd按需加載

yarn run eject

->~ yarn create react-app my-app
->~ cd my-app
->~ yarn run eject | npm run eject


image.png

運行成功后eject后會暴露webpack的配置,package.json中也會列出所有相關依賴包,如:

  • config目錄
  • build.js / start.js / test.js
  • package.json / yarn.lock 會更新

安裝antd 按需加載

->~ yarn add antd | npm install antd --save | cnpm install antd --save (--save 安裝到生產環境dependencies、--seve-dev 代表安裝到開發本地devDependencies)
->~ yarn add babel-plugin-import -D | --dev (yarn add) | npm install babel-plugin-import --save-dev babel-plugin-import
根目錄新建:.babelrc文件 添加:

{
  "plugins": [
    ["import", { "libraryName": "antd", "libraryDirectory": "lib"}, "ant"],
    ["import", { "libraryName": "antd-mobile", "libraryDirectory": "lib"}, "antd-mobile"]
  ]
}

注意:如果是運行了eject ,webpack配置了babelrc: false ,單獨根目錄新建.babelrc會報錯的,需要在webpack.dev.js配置,在module模塊 ,loader: require.resolve('babel-loader')對象中的plugins數組中添加

[
  "import",
  {libraryName: "antd", style: 'css'} // 移動端添加 "libraryName": "antd-mobile"
] //antd按需加載

完整的:


image.png

運行查看效果:

->~ npm start

image.png
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容