头图

How to elegantly use SVG font icons in WeChat Mini Programs

pingan8787
中文
The idea of this article comes from the refactoring summary of the actual project, welcome to correct and communicate. If it is helpful to you, please also like it 👍Favorite to support it.

Recently I am refactoring a project, mainly for H5 and small programs. This time I plan to start to summarize more. I have already summarized an article "How to elegantly manage HTTP request and response interceptors?" 》 .

If you have other plans, welcome to discuss it together~ Friends who like this article give me a thumbs up 👍 encourage you~

1. Demand thinking and plan design

The project introduced in this article uses the Taro framework for multi-terminal development, and currently it is mainly adapted to the H5 terminal and WeChat applet terminal. The font icon library used by the project is maintained internally and is currently hosted on iconfont .

1. Problem analysis

The recently refactored project is relatively old (in fact, it was last year). The icons used in the project have been updated for N iterations. It has been updated from monochrome icon to multicolor icon !

Obviously it's much better.

Here, first follow the iconfont rule see the difference in the use of single-color icons and multi-color icons:

Use of monochrome icons

Monochrome icons are relatively simple to use (take font-class reference as an example), and only need 2 steps:

  • Step 1: Copy the fontclass code generated under the project:

    //at.alicdn.com/t/font_8d5l8fzk5b87iudi.css
  • Step 2: Select the corresponding icon and get the class name to apply to the page:

    <i class="iconfont icon-xxx"></i>

Use of multi-color icons

Multi-color icons are also very simple to use (take symbol reference as an example), and only need 3 steps:

  • Step 1: Copy the symbol code generated under the project:

    //at.alicdn.com/t/font_8d5l8fzk5b87iudi.js
  • Step 2: Add general css code (introduce it once):

    <style type="text/css">
      .icon {
         width: 1em; height: 1em;
         vertical-align: -0.15em;
         fill: currentColor;
         overflow: hidden;
      }
    </style>
  • Step 3: Select the corresponding icon and get the class name, and apply it to the page:

    <svg class="icon" aria-hidden="true">
      <use xlink:href="#icon-xxx"></use>
    </svg>

Both of these icons are very convenient to use, so everyone will be curious, the purpose of our writing this article?

The reason is that SVG font icons are not supported on the 😔 Multi-color icons need to be implemented with the help of SVG tags.

So I applet document a long time, and only saw that the <Image> component can use SVG. The introduction is as follows:

image picture. Supports formats such as JPG, PNG, SVG, WEBP, GIF, and cloud file IDs starting from 2.3.0.

The value of the attribute src is the address of the image resource, which means that SVG font icons cannot be used. So we need to think of workarounds.

(I don’t discuss the case of downloading the icons on iconfont as pictures for reference)

2. Scheme design

Now that we understand how to use single-color icons and multi-color icons:

  • Monochrome icon: any label (such as div label) + corresponding font icon class name
  • Multi-color icon: use the svg label + use label to set the xlink:href attribute

The first thing that comes to my mind immediately is, can we combine the two ways to use multi-color icons for any label through the class name?

The answer is yes, only the format conversion of the icon file is required, that is, converts the multi-color font icon into a font icon file can be referenced by the class name.

Then just take a look at how to achieve format conversion.

Second, the effect after reconstruction

Here I refactored one of the pages, and finally replaced all the monochrome icons with new multi-color SVG font icons. The effect is as follows:

3. Solution 1: Manually convert icon files

At present, I have tried two sets of plans, and both have achieved the effect smoothly. Here, I will share these two plans first, and then I will explain which plan I choose and why:

What this solution achieves is to manually convert the font icon library file into an icon library that can be referenced by the class name.
The tools used are:

  1. icomoon: https://icomoon.io/ used to package icons.
  2. transfonter: https://transfonter.org/ used to generate icons in base64 format.

Then start to try:

Step 1: Download the required SVG format icon through iconfont

I downloaded a few more files here, all in svg format, as shown below:

Step 2: Pack font icons

This step is to pack scattered multiple SVG multi-color icons into a font icon file, this step needs to use https://icomoon.io/ :

Step 3: Base64 encoding the font icon

Next, you need to base64 compress the font icons. Here, use 16100e4606d77b https://transfonter.org/ to operate.

The first step is to select the .ttf file in the previously printed package:

Set the parameters and export the file:

Step 4: Combine font icons

After the previous steps, we now have 2 packages:

  • The first package: the package generated by icomoon

  • The second package: the package generated by transfonter

Next we start to merge the two packages:
Copy the contents of the first package style.css file except @font-face to the second package stylesheet.css file.

In this way, a new font icon file is obtained, in fact, it can also be copied to a new css file.

Use font icons

We renamed the previously modified file to icon.scss and introduced it to the project:

// app.scss

@import "./style/icon.scss";

Icons used in the code:

<View className="icon-exe-knowledge-ppt">
  <View className='path1'></View>
  <View className='path2'></View>
  <View className='path3'></View>
  <View className='path4'></View>
  <View className='path5'></View>
  <View className='path6'></View>
</View>

The final effect is as follows:

Pit record

When using plan one, I stepped on several pits. Here are two of them:

  • When using, you need to manually add a few <View classname="path*"></View> elements

When I first started using it, the icon never came out. I will observe the font icon later. It is to render the icon content in the pseudo-classes path1 and path2

So you need to add it manually when you use it.

  • The default icon will be a large block-level element, causing problems with the icon display

This is because the manually added View path* is a block-level element, so just simply add display: flex here.

And its font size can also be set font-size

display: flex;
font-size: 100px;

Extract components

Considering the reusability, I exe-svg-icon these into a 06100e4606d9fb component:

import Taro from '@tarojs/taro';
import { View, Text } from '@tarojs/components';
import classNames from 'classnames';

function EXESvgIcon(params) {
  const { icon = 'exe-none' } = params;
  const containerStyle = {
    display: 'inline-block'
  }
  return (
    <View className={classNames('svg', icon)} style={containerStyle}>
      <View className='path1' style={containerStyle}></View>
      <View className='path2' style={containerStyle}></View>
      <View className='path3' style={containerStyle}></View>
      {/* 一般图标 3 层,这边多预留几层,防止不够用 */}
      <View className='path4' style={containerStyle}></View>
      <View className='path5' style={containerStyle}></View>
      <View className='path6' style={containerStyle}></View>
      <View className='path7' style={containerStyle}></View>
      <View className='path8' style={containerStyle}></View>
      <View className='path9' style={containerStyle}></View>
    </View>
  )
}
export default EXESvgIcon;

At this point, the first implementation of the program is completed.

Fourth, program two: implement with the help of third-party libraries

Since the first scheme is more cumbersome to use, I will study other simple schemes.

Until I saw the taro-iconfont-cli library.

Use iconfont icons in the Taro framework, independent of fonts, and support for multiple colors.

Currently supported platforms include:

  • WeChat Mini Program
  • Alipay applet
  • Baidu Mini Program
  • Headline applet
  • QQ applet
  • H5

Has the following characteristics:

  • One-key generation of standard components, multi-terminal support
  • Easy to use, just import
  • Support multiple colors
  • Support custom colors
  • Support both ES6 and TypeScript modes

According to the document description, only 3 steps are required, so give it a try:

Step 1: Install taro-iconfont-cli

# Yarn
yarn add taro-iconfont-cli --dev

# Npm
npm install taro-iconfont-cli --save-dev

Note that if you are using Taro 2.x, please install **taro-iconfont-cli@2.1.0** and read the old version of README.md .

Step 2: Generate configuration file

Generate iconfont.json configuration file by command:

npx iconfont-init

# 可传入配置输出路径
# npx iconfont-init --output iconfont.json

iconfont.json will be generated in the root directory of the project, with the content as follows:

{
  "symbol_url": "请参考README.md,复制 http://iconfont.cn 官网提供的JS链接",
  "save_dir": "./src/components/iconfont",
  "use_typescript": false,
  "platforms": "*",
  "use_rpx": true,
  "trim_icon_prefix": "icon",
  "default_icon_size": 18,
  "design_width": 750
}

symbol_url value needs to be copied in iconfont

Step 3: Generate Taro standard components

Generate Taro standard components by command:

npx iconfont-taro

# 可传入配置文件路径
# npx iconfont-taro --config iconfont.json

Through the console, we can see that taro-iconfont-cli generates a separate Taro component for each icon:

Use font icons

According to the document usage method, when using it, you only need to introduce the IconFont component, and select the corresponding icon name

// 省略其他代码

import IconFont from '@components/Iconfont/index';

<IconFont name="exe-knowledge-ppt"></IconFont>

According to the documentation, there are more ways to use it:

// 原色彩
<IconFont name="alipay" />

// 单色:红色
<IconFont name="alipay" color="red" />

// 多色:红色+橘色
<IconFont name="alipay" color={['red', 'orange']} size={300} />

// 不同格式的颜色写法
<IconFont name="alipay" color={['#333', 'rgb(50, 124, 39)']} />

// 与文字对齐
<View style={{ display: 'flex', alignItems: 'center' }}>
  <Text>Hello</text>
  <IconFont name="alipay" />
</View>

Pit record

  1. Font size setting problem

Since the icon exported in this way is a separate component, if you need to set the icon size when using it, you need to set its properties width and height

The size of the font icon cannot be set through the font-size

Five, plan comparison and selection

This time I only tried these two schemes, and the requirements were successfully completed. If you have other plans, welcome to discuss together in the comment section~

Next, will generate the same 20 multi-color icons below as the standard, and analyze the two schemes:

First look at the comparison results:

Manually convert icon files With taro-iconfont-cli library implementation
Generation difficulty level complexsimple
use simplesimple
Resource occupancy level 27kb420kb (before the project is packaged)

Analyze each item:

1. Compare the difficulty of generation

  • "Manually convert icon files" needs to download the icons separately and then pack them each time. When the number of icons is large, the workload is relatively large.
  • "Taro-iconfont-cli" only needs to set the address of the font icon library, and automatically download and generate components, which is more convenient.

2. Compare the ease of use

Both are relatively simple to use:

  • "Manually convert icon files" just add the class name to the element.
  • "Taro-iconfont-cli" adds a name attribute to the element.

    3. Compare resource usage

    The resource occupancy difference is very big, analyze the reasons below:

  • "Manually Convert Icon File" is to repackage the icon, and the final generated content is base64 encoded, which is relatively small.
  • "Taro-iconfont-cli" is to generate a component for each icon, a separate file, and additional files for each platform, so it is larger.

    4. Choose a plan

    Considering that the font icons used in the current project are relatively small (less than 20), and the difficulty of subsequent developers to get started, I finally use the "taro-iconfont-cli" solution.
    Although the resource usage of the components generated by this solution will be slightly larger, currently there are fewer icons and can be optimized through common optimization methods such as packaging tools and CDN.

6. Summary of this article

Through a simple project refactoring, this article summarizes the scheme of using SVG multi-color icons in small programs in the project. The purpose is to realize the normal use of SVG multi-color icons in small programs, and also accumulate content for more and more independent sites. Experience, after all, each project is relevant.

Finally, the "taro-iconfont-cli" solution is currently maintained in the internal npm warehouse, using version control to facilitate the use of different projects to reduce conflicts.

Of course, this article is based on my experience, welcome everyone to have a better plan, discuss and learn together~~

Reference article

阅读 1.7k

前端自习课
pingan8787前端开发学习记录
2.5k 声望
2.1k 粉丝
0 条评论
你知道吗?

2.5k 声望
2.1k 粉丝
宣传栏