antd-mobile定制主题
2020-08-26
create-react-app
与antd-mobile
构建项目,主题不符合,遂改变主题
准备工作:
- 构建新react项目
create-react-app projrct-name
- 导入
antd-mobile
:npm install antd-mobile --save
- 为了使项目最小化,我使用按需加载方式引入
正文
按需加载:
npm install react-app-rewired customize-cra babel-plugin-import --save-dev
- 根目录创建:
config-overrides.js
, 该文件用来修改默认配置
- 初始化文件
module.exports = function override(config, env) {
// do stuff with the webpack config...
return config;
};
- 修改
package.json
, 原本由react-scripts
启动的脚本改为react-app-rewired
, 如下
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject",
"client": "serve build"
}
- 修改
config-overrides.js
文件, 修改后文件如下
const { override, fixBabelImports } = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd-mobile',
style: true
})
);
- 更改引用方式
import { Button } from 'antd-mobile';
至此,实现了按需引入
改变主题
- 下载所需依赖:
npm install --save-dev babel-plugin-import less less-loader style-loader css-loader
- 无需暴露
webpack
配置,直接在config-overrides.js
文件修改,修改文件如下
const { override, fixBabelImports, addLessLoader } = require('customize-cra');
module.exports = override(
addLessLoader({
javascriptEnabled: true,
modifyVars: {
'@brand-primary': '#ff00ff',
'@color-text-base': '#333',
}
}),
fixBabelImports('import', {
libraryName: 'antd-mobile',
libraryDirectory: 'es',
style: true
})
);
- 自定义
theme.json
文件,我放在项目根目录
{
"@brand-primary": "#1cae82",
"@brand-primary-tap": "#1da57a"
}
- 修改
config-overrides.js
const { override, fixBabelImports, addLessLoader } = require('customize-cra');
// ---------导入样式文件
const theme = require('./theme.json');
module.exports = override(
addLessLoader({
javascriptEnabled: true,
modifyVars: theme
}),
fixBabelImports('import', {
libraryName: 'antd-mobile',
libraryDirectory: 'es',
style: true
})
);
- 重启项目,然后你会发现
less-loader6.0+
报错了,哈哈哈哈哈,
报错信息如下:
ValidationError: Invalid options object. Less Loader has been initialized using an options object that does not match the API schema.
这是因为less-loader6.0+
的兼容问题,两个解决办法
- 第一种: 移除
less-loader@6.0.0
并install less-loader@5.0.0
- 第二种: 修改
config-overrides.js
文件
const { override, fixBabelImports, addLessLoader } = require('customize-cra');
const theme = require('./antd-theme.json');
module.exports = override(
addLessLoader({
lessOptions: {
javascriptEnabled: true,
modifyVars: theme
}
}),
fixBabelImports('import', {
libraryName: 'antd-mobile',
libraryDirectory: 'es',
style: true
})
);
- 然后再停掉重启项目,终于 ok 了
参考:
https://mobile.ant.design/docs/react/use-with-create-react-app-cn