ant Design和ant Design mobile的使用,並實現按需加載

1.全局安裝yarn css

npm install -g create-react-app yarn

 

2.建立react項目,並用yarn start 運行react

 

3.引入antd/引入antd-mobilewebpack

yarn add antd

 

yarn add antd-mobile

 

4.在app.js引入buttonweb

pc端npm

import Button from 'antd/lib/button';
 <div className="App">
        <Button type="primary">Button</Button>
      </div>

 移動端json

import Button from 'antd-mobile/lib/button';
<div className="App">
        <Button type="primary">Button</Button>
      </div>

 

5.修改 src/App.css,在文件頂部引入 antd/dist/antd.cssbabel

pc端antd

@import '~antd/dist/antd.css';

 移動端app

@import '~antd-mobile/dist/antd-mobile.css';

 

6.按需加載模塊ide

yarn add react-app-rewired@2.0.2-next.0

 

7.修改package.json,綠色替換紅色

/* 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", +   "test": "react-app-rewired test",
}

 

8. 根目錄建立 config-overrides.js,添加以下代碼

module.exports = function override(config, env) {
  // do stuff with the webpack config...
  return config;
};

 

9.使用 babel-plugin-import

yarn add babel-plugin-import

 

10.用下面代碼覆蓋config-overrides.js的代碼

pc端

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

 移動端

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

 

11.修改app.css代碼

pc端

@import '~antd/dist/antd.css';   // 刪除

import Button from 'antd/lib/button';  // 刪除

import { Button } from 'antd'; // 添加

 移動端

@import '~antd-mobile/dist/antd-mobile.css';   // 刪除

import Button from 'antd-mobile/lib/button';  // 刪除

import { Button } from 'antd-mobile'; // 添加

 

12.yarn start從新運行

 

 

按照上面的操做就能夠了

相關文章
相關標籤/搜索