在webpack自定义配置antd的按需加载和修改主题色

最近使用antd来作react项目的UI。从antd官网上,在使用create-react-app脚手架搭建项目时步骤以下:javascript

(1)添加模块 react-app-rewired, babel-plugin-import, react-app-rewire-lesscss

(2)根目录添加config-overrides.jsjava

(3)修改npm script便可, 一切正常react

参考官网webpack

 

这里主要说的是自建的react项目中如何配置及其容易出现的坑web

1、按需加载npm

  (1)在.babelrc中添加plugins (这里也能够在babel-loader的options中添加)json

1 ['import', { 
2     libraryName: 'antd', 
3     libraryDirectory: 'es',
4     style: 'css' 
5     }
6 ]

  注意该步很容易有报错:数组

.bezierEasingMixin();Inline JavaScript is not enabled. Is it set in your options?
此时检查package.json中看看less的版本是不是3.x, 若是时降为less@2.7.3
再重启项目,搞定。

 

2、修改主题色sass

找到webpack.config.js的less-loader, 在options中添加

 1 {
 2      loader: 'less-loader',
 3      options: {
 4         sourceMap: true,
 5         modifyVars: {
 6            'primary-color': '#1DA57A',
 7            'link-color': '#1DA57A',
 8            'border-radius-base': '2px'
 9          },
10      javascriptEnabled: true   // 此项不能忘
11   }
12 }

此处有个坑,以前使用ExtractTextPlugin插件对css样式提取,但如配置主题色修改,不能再使用提取插件,另外,找到.babelrc中找到以前按需加载的配置修改:

1 ['import', { 
2      libraryName: 'antd', 
3      style:  true
4      }
5 ]

删除以前的 libraryDirectory: 'es',

修改以前的 style: "css" 为 style: true

修改主题是基于less提供的modifyVars变量进行修改的,因此按需加载时使用true

主题定制

 

新版create-react-app脚手架中修改antd主题配置

(1) 引入UI库

 

 注意,这里import后面是一个对象,而不是数组

 (2) 添加less的正则

 

(3) 在sass规则后面添加less规则

 

 

 (4) 修改getStyleLoaders方法

 

 改为

 

 注意less版本还需使用2.7.3

重启项目,完成修改。

相关文章
相关标签/搜索