create-react-app与antd一起使用The "injectBabelPlugin" helper has been deprecated as of v2.0. You can use
全局安装create-react-app
npm install create-react-app -g
//用它创建项目
create-react-app react-demo
//启动项目
npm run start
然后安装antd
npm install antd --save
按需引入Ant-Design插件
需要两个插件:
1、react-app-rewired(一个对 create-react-app 进行自定义配置的社区解决方案)。
git地址:https://github.com/timarney/react-app-rewired/
npm install react-app-rewired -D
/* 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 用于修改默认配置。
module.exports = function override(config, env) {
// do stuff with the webpack config...
return config;
};
2、babel-plugin-import (一个用于按需加载组件代码和样式的 babel 插件)。
npm install babel-plugin-import -D
修改 config-overrides.js 文件。
const { injectBabelPlugin } = require('react-app-rewired');
module.exports = function override(config, env) {
config = injectBabelPlugin(['import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css' }], config);
return config;
};
经过上面两部的操作,我们的antd的按需引入就设置好了。在组件中直接这么用
随后我就启动项目:
$ npm run start
> [email protected] start E:\aPritice\appnfc
> react-app-rewired start
The "injectBabelPlugin" helper has been deprecated as of v2.0. You can use customize-cra plugins in replacement - https://github.com/arackaf/customize-cra#available-plugins
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `react-app-rewired start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\zoe\AppData\Roaming\npm-cache\_logs\2019-04-30T07_08_42_894Z-debug.log
就直接报错了,跟着报错,进到这里https://github.com/arackaf/customize-cra#available-plugins
,就看到一句话:Override webpack configurations for create-react-app 2.0,react-scripts 升级到 2.1.2 以后破坏了 react-app-rewired,react-app-rewired的新版本删除所有方法injectBabelPlugin,这些方法被移动到一个名为’customize-cra’的新包中了
所以现在你可以开始下载这个包还有less,less-loader了
npm 方法:
npm install customize-cra --save-dev
npm i less
npm i -D less-loader
yarn方法:
yarn add customize-cra --dev
yarn add less
yarn add --dev less-loader
下载完,修改下
config-overrides.js
const {
override,
fixBabelImports,
// addLessLoader,
} = require("customize-cra");
module.exports = override(
fixBabelImports("import", {
libraryName: "antd", libraryDirectory: "es", style: 'css' // change importing css to less
}),
// addLessLoader({
// javascriptEnabled: true,
// modifyVars: { "@primary-color": "#1DA57A" }
// })
);
然后就可以重新
npm run start
然后页面就可以正常运行了