react按需引入antd,修改antd样式主题
安装插件安装ant-design:
yarn
yarn add antd
npm
npm install antd
安装@ant-design/icons 图标组件包:
yarn
yarn add @ant-design/icons
npm
npm install @ant-design/icons
按需引入插件安装:
yarn
yarn add react-app-rewired customize-cra babel-plugin-import
npm
npm install react-app-rewired customize-cra babel-plugin-import
自定义主题安装less 和 less-loader
yarn
yarn add less less-loader
npm
npm install less less-loader
2. 选项配置
装依赖并修改package.json
此时我们需要对 create-react-app 的默认配置进行自定义,这里我们使用 react-app-rewired (一个对 create-react-app 进行自定义配置的社区解决方案)。
修改package.json中scripts节点:
/* package.json */
“scripts”: {
“start”: “react-app-rewired start”,
“build”: “react-app-rewired build”,
“test”: “react-app-rewired test”,
“eject”: “react-scripts eject”
},
在项目根目录新建一个名为config-overrides.js的文件
按需引入组件和组件css样式表配置代码:
const { override, fixBabelImports } = require(‘customize-cra’);
module.exports = override(
fixBabelImports(‘import’, {
libraryName: ‘antd’,
libraryDirectory: ‘es’,
style: ‘css’,
}),
);
按需引入+自定义主题配置代码:
const { override, fixBabelImports, addLessLoader, adjustStyleLoaders } = require(‘customize-cra’);
module.exports = override(
fixBabelImports(‘import’, {
libraryName: ‘antd’,
libraryDirectory: ‘es’,
style: true,
}),
addLessLoader({
lessOptions: {
javascriptEnabled: true,
modifyVars: { ‘@primary-color’: ‘#1DA57A’ },
}
}),
adjustStyleLoaders(({ use: [, , postcss] }) => {
const postcssOptions = postcss.options;
postcss.options = { postcssOptions };
})
);
按需引入+自定义主题配置代码:
const { override, fixBabelImports, addLessLoader, adjustStyleLoaders } = require(‘customize-cra’);
module.exports = override(
fixBabelImports(‘import’, {
libraryName: ‘antd’,
libraryDirectory: ‘es’,
style: true,
}),
addLessLoader({
lessOptions: {
javascriptEnabled: true,
modifyVars: { ‘@primary-color’: ‘#1DA57A’ },
}
}),
adjustStyleLoaders(({ use: [, , postcss] }) => {
const postcssOptions = postcss.options;
postcss.options = { postcssOptions };
})
);