react中执行yarn eject配置antd-mobile的
在使用react做项目时如果用antd-mobile,
如果使用按需加载,则需要修改它的配置文件如果我们不操作yarn eject,
则直接操作下面的步骤即可:
在create-react-app 搭建脚手架时cnpminstall-gcreate-react-appcreate-react-app reactDemocd reactDemocnpmstart
引入 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里面引入的总样式需要删掉)
-importButtonfrom'antd-mobile/lib/button';
+import{ Button }from'antd-mobile';
如果执行yarn eject,
需要配置的操作如下1.用create-react-app创建完成项目后,
执行yarn eject命令后会生成一个config文件,
在config文件夹会显示配置文档
2.添加插件 yarnaddbabel-plugin-import--save-dev yarnaddantd--save-dev
3.在congif文件夹下webpack.config.dev.js options: {
+ plugins: [ + [‘import‘, [{ libraryName:"antd",style: ‘css‘ }]], + ],
// Thisisa featureof`babel-loader`forwebpack (notBabel itself).
// It enablescachingresultsin./node_modules/.cache/babel-loader/ //directoryforfaster rebuilds. cacheDirectory:true, },
4.在config文件下webpack.config.prod.js添加
options: { + plugins: [
+ [‘import‘, [{ libraryName:"antd",style: ‘css‘ }]], +
],
compact:true,
},
5.在页面引入antdimport{ Button }from'antd-mobile';