react中執行yarn eject配置antd-mobile的按需加載

在使用react做項目時如果用antd-mobile,如果使用按需加載,則需要修改它的配置文件
如果我們不操作yarn eject,則直接操作下面的步驟即可:

在 create-react-app 搭建腳手架時
cnpm install -g create-react-app
create-react-app reactDemo
cd  reactDemo
cnpm start
引入 antd-mobile
因爲配置文件隱藏了,從而我們需要引入 react-app-rewired 並修改 package.json 裏的啓動配置

cnpm install react-app-rewired --save-dev
cnpm install babel-plugin-import --save-dev
或者
yarn add react-app-rewired --dev
yarn add babel-plugin-import --dev
/* package.json 的配置需要做如下修改*/
"scripts": {
-   "start": "react-scripts start",
+   "start": "react-app-rewired start",
-   "build": "react-scripts build",
+   "build": "react-app-rewired build",
-   "test": "react-scripts test --env=jsdom",
+   "test": "react-app-rewired test --env=jsdom",
}

然後在項目根目錄創建一個 config-overrides.js 用於修改默認配置(必須是根目錄下)。

const {injectBabelPlugin} = require('react-app-rewired');
module.exports = function override(config, env) {
  config = injectBabelPlugin(['import', {libraryName: 'antd-mobile', style: 'css'}], config);
  return config;
};

此頁面的引入方式更改爲(index.js裏面引入的總樣式需要刪掉)
- import Button from 'antd-mobile/lib/button';
+ import { Button } from 'antd-mobile';
如果執行yarn eject,需要配置的操作如下

1.用create-react-app創建完成項目後,執行yarn eject命令後會生成一個config文件,在config文件夾會
顯示配置文檔
2.添加插件
   yarn add babel-plugin-import --save-dev 
   yarn add antd --save-dev 
3.在congif文件夾下webpack.config.dev.js
  options: {
   +        plugins: [
   +             [‘import‘, [{ libraryName: "antd", style: ‘css‘ }]],
   +          ],
              // 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,
            },
4.在config文件下webpack.config.prod.js添加
     options: {
     +        plugins: [
     +             [‘import‘, [{ libraryName: "antd", style: ‘css‘ }]],
     +         ],
              compact: true,
            },
5.在頁面引入antd
    import { Button } from 'antd-mobile';       
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章