實現Ant Design按需加載

首先安裝babel-plugin-import:

npm i babel-plugin-import -S

然後在.babelrc中添加如下代碼:

// .babelrc or babel-loader option
{
  "plugins": [
    ["import", { libraryName: "antd", style: "css" }] // `style: true` 會加載 less 文件
  ]
}

但如果是用的create-react-app腳手架的話,初始的根目錄裏並沒有.babelrc文件,那就自己新建一個。

babelrc配置完之後,把項目跑起來發現並不起作用,組件樣式並沒有加上。

這裏其實錯的不是我們,也不是antd,而是這個腳手架它默認是不使用.babelrc的,可以在

node_modules/react-scripts/config/webpack.config.js中看到babelrc: false

{
              test: /\.(js|mjs|jsx|ts|tsx)$/,
              include: paths.appSrc,
              loader: require.resolve('babel-loader'),
              options: {
                customize: require.resolve(
                  'babel-preset-react-app/webpack-overrides'
                ),
                // @remove-on-eject-begin
                babelrc: false,
                configFile: false,
                presets: [require.resolve('babel-preset-react-app')],
                // Make sure we have a unique cache identifier, erring on the
                // side of caution.
                // We remove this when the user ejects because the default
                // is sane and uses Babel options. Instead of options, we use
                // the react-scripts and babel-preset-react-app versions.
                cacheIdentifier: getCacheIdentifier(
                  isEnvProduction
                    ? 'production'
                    : isEnvDevelopment && 'development',
                  [
                    'babel-plugin-named-asset-import',
                    'babel-preset-react-app',
                    'react-dev-utils',
                    'react-scripts',
                  ]
                ),
                // @remove-on-eject-end
                plugins: [
                  [
                    require.resolve('babel-plugin-named-asset-import'),
                    {
                      loaderMap: {
                        svg: {
                          ReactComponent:
                            '@svgr/webpack?-svgo,+titleProp,+ref![path]',
                        },
                      },
                    },
                  ],
                ],
                // 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,
                // See #6846 for context on why cacheCompression is disabled
                cacheCompression: false,
                compact: isEnvProduction,
              },
            }

只要把false改成true再重新“npm run start”一下就好了。

後面用的antd組件的地方直接引用就行了,不用再去引樣式。

import { Button } from 'antd';

注意,如果webpack中css-loader在options中配置了modules:

    module: { // 所有第三方模塊的配置規則
        rules: [ // 第三方匹配規則
            {
                test: /\.js|jsx$/,
                use: "babel-loader",
                exclude: /node_modules/ // exclude千萬別忘記
            },
            {
                test: /\.css$/,
                use: [
                    {loader: "style-loader"}, 
                    {
                        loader: "css-loader",
                        options: {
                            modules: {
                                localIdentName: "[path][name]-[local]-[hash:5]"
                            }
                        }
                    }]
            }
        ]
    }

這樣會開啓css-module,會默認對所有的類名與動畫名啓用局部作用域css,最後導致Ant Design樣式不生效。

以下爲一個and design modal組件:

import React, { Component } from 'react';
import { Modal, Button } from 'antd';

export default class ThisModal extends Component {
    state = { visible: false };

    showModal = () => {
        this.setState({
            visible: true,
        });
    };

    handleOk = e => {
        console.log(e);
        this.setState({
            visible: false,
        });
    };

    handleCancel = e => {
        console.log(e);
        this.setState({
            visible: false,
        });
    };

    render() {
        return (
            <div>
                <Button type="primary" onClick={this.showModal}>
                    Open Modal
        </Button>
                <Modal
                    title="Basic Modal"
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >
                    <p>Some contents...</p>
                    <p>Some contents...</p>
                    <p>Some contents...</p>
                </Modal>
            </div>
        )
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章