antd-mobile定制主题

2020-08-26


create-react-appantd-mobile 构建项目,主题不符合,遂改变主题

准备工作:

  1. 构建新react项目 create-react-app projrct-name
  2. 导入antd-mobilenpm install antd-mobile --save
  3. 为了使项目最小化,我使用按需加载方式引入

正文

按需加载:

  1. npm install react-app-rewired customize-cra babel-plugin-import --save-dev
  2. 根目录创建: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';
    至此,实现了按需引入

改变主题

  1. 下载所需依赖:
    npm install --save-dev babel-plugin-import less less-loader style-loader css-loader
  2. 无需暴露 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
  })
);
  1. 自定义 theme.json文件,我放在项目根目录
{
  "@brand-primary": "#1cae82",
  "@brand-primary-tap": "#1da57a"
}
  1. 修改 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
  })
);

  1. 重启项目,然后你会发现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.0install 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
  })
);

  1. 然后再停掉重启项目,终于 ok 了

参考:

https://mobile.ant.design/docs/react/use-with-create-react-app-cn

https://www.jianshu.com/p/7097348cd900

https://github.com/ant-design/ant-design-landing/issues/235

posted on 2020-08-27 10:30  爱IT的小狐狸  阅读(785)  评论(0编辑  收藏  举报