Package and load OTF custom fonts in Ant Design Pro

When using Webpack to package font files, you need to use file-loader to process the packaging file. In Ant Design Pro, you can customize the Webpack configuration by using the chainWebpack function in the configuration file.

1, install,file-loader

npm install --save-dev file-loader
Copy the code

2. Edit the Ant Design Pro configuration fileconfig/config.tsIn thechainWebpack

export default defineConfig({
  // ...
  chainWebpack(config){
    config.module / / configuration file - loader
      .rule('otf')
      .test(/.otf$/)
      .use('file-loader')
      .loader('file-loader'); }});Copy the code

Declare fonts in the LESS style file

@font-face {
  font-family: Pangram-Black;
  src: url('.. /font/Pangram-Black.otf'), url('.. /font/Pangram-Black.otf');
  font-display: swap;
}
Copy the code

4. Use stated fonts

.fontFamilyPangramBlack {
  font-weight: 700;
  font-family: Pangram, Pangram-Black;
}
Copy the code

Pay attention to

This is required when using @import to reference SRC files in less files, because CSS Loaders interpret urls that are not root paths as relative paths and prefix them with ~ to interpret them as module paths.

@import "~@/assets/style/_mixin";
Copy the code

Ant Design Pro offline reference iconFont, including menus and components used

Due to the official case is based on the network JS file, on the local offline introduction of the case is very few, and a variety of articles are not the same, and modify the source code, this is obviously very inconvenient. It doesn’t have to be that complicated, just put your downloaded iconfont. Js in a public directory and import it in the appropriate place.

1, downloadiconfontfile

After the iconfont file is generated and downloaded, iconfont. Js is placed in the pubilc directory

2. Configure the icon used in the menu

Config /defaultSettings will automatically load iconfont. Js in public

. iconfontUrl: 'iconfont.js', ...Copy the code

3. Configure the icon used in the component

Component use requires the installation of @ant-design/ ICONS in the project

Yarn add @ant-design/ ICONS --save // or NPM I @ant-design/ ICONS --saveCopy the code
import { createFromIconfontCN } from "@ant-design/icons"

const IconFont = createFromIconfontCN({
  scriptUrl: 'iconfont.js'.// Also directly iconfont. Js
});

function IconExample() {
    return (
        <IconFont type="Your icon name"/>)}Copy the code

When developing with Ant Design Pro, I found that installing dependencies didn’t work, nor did refreshing

Because Ant Design Pro uses caches during development to speed up builds, data in the cache is used by default when a dependency is repeatedly installed, or versions of dependencies are changed many times. As a result, sometimes the refresh is useless.

Solution: Delete the generated dist file and the SRC /.umi directory and run the project over again