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';       

猜你喜欢

转载自blog.51cto.com/12885303/2156443