Ant Design 按需加载与 Less 更改主题

2018-11-07  本文已影响0人  双面小Q

最近做项目时,使用create-react-app脚手架引入Ant Design,官网教程是采用不抛出webpack配置,利用react-app-rewired来修改脚手架默认webpack配置,详情可查看官网教程:在 create-react-app 中使用

而使用yarn eject抛出脚手架的内建webpack配置需要自行探索,下面就简单介绍下配置教程:

  1. 安装babel-plugin-import
yarn add babel-plugin-import --dev
  1. 修改webpack.config.dev.js

找到babel-loader配置的地方,添加按需加载 Ant Design的配置

['import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css' }]
// Process application JS with Babel.
// The preset includes JSX, Flow, and some ESnext features.
{
  test: /\.(js|mjs|jsx|ts|tsx)$/,
  include: paths.appSrc,
  loader: require.resolve('babel-loader'),
  options: {
    customize: require.resolve('babel-preset-react-app/webpack-overrides'),

    plugins: [
      [
        require.resolve('babel-plugin-named-asset-import'),
        {
          loaderMap: {
            svg: {
              ReactComponent: '@svgr/webpack?-prettier,-svgo![path]'
            }
          }
        }
      ],
      // Ant Design 按需加载
      ['import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css' }]
    ],
    // This is a feature of `babel-loader` for webpack (not Babel itself).
    // It enables caching results in ./node_modules/.cache/babel-loader/
    // directory for faster rebuilds.
    cacheDirectory: true,
    // Don't waste time on Gzipping the cache
    cacheCompression: false
  }
}
  1. 安装lessless-loader
yarn add less less-loader --dev
  1. 修改webpack.config.dev.js

在上面按需加载的配置处修改style: 'css'style: true

['import', { libraryName: 'antd', libraryDirectory: 'es', style: true }]
  1. 添加less配置信息
// 引入 Less 配置
{
  test: /\.less$/,
  use: [
    'style-loader',
    'css-loader',
    {
      loader: 'less-loader',
      options: {
        modifyVars: { '@primary-color': '#1DA57A' },
        javascriptEnabled: true
      }
    }
  ]
}
上一篇下一篇

猜你喜欢

热点阅读