preface

This article has been written on and off for almost half a year. The main part has been written for a long time, but it has not been published for various reasons. First of all, the main intention of writing this article is that many ICONS are often used in front-end and background projects. At the beginning, it is ok, but with the continuous iteration of the project, it becomes very troublesome to modify and add ICONS every time, and I always feel that it is not elegant enough, so I start to wonder what is a simple and convenient workflow?

evolution

First, let’s talk about the history of the front-end icon.

In ancient times when I started my internship, MOST of the ICONS were implemented using IMG. Gradually found that a page request resources in the image IMG accounted for the majority, so in order to optimize the image Sprite is the so-called Sprite diagram, is to combine multiple images into a picture, and then use CSS backspace-position positioning display different icon ICONS. But this also has a big pain point, it’s difficult to maintain. Every new icon, you need to change the original picture, but also may accidentally error affect the previous positioning of the good picture, and once you modify Sprite diagram, the image cache is invalid, over time you do not know how to maintain.

Font libraries Over time a project would almost never use any native images, and would use some font libraries to implement page ICONS. Common ones, such as Font Awesome, are also very convenient to use, but it has a fatal disadvantage that it is really inconvenient to find, and it takes a lot of eyes to find an icon every time. In addition, its customization is also very unfriendly. There are 675 ICONS in its icon library. Still, it’s often the case that you can’t find the icon you need. Of course, it can be tolerated by a startup that doesn’t have a particular UI to pursue. But as the company got bigger, there were more and more people who were at the front, crazy designers, and they said no! This icon is so ugly, it is an insult to their title of senior designer! But that’s when iconfont came along.

“Iconfont, an open source stock made by Ali’s dad, also had its own Github issue(although one of mine had not responded for more than six months), but the number of ICONS was striking, with not only the hundreds of companies’ open source libraries, but also a wide variety of other smaller ICONS, It also allows you to create custom icon libraries, so whether you’re a startup or a design-oriented company, it’s a great way to get around the pain points of managing ICONS. You have almost everything you want

Iconfont three postures

unicode

At first we used the Unicode format, and its main feature is the advantage

  • The best compatibility, support IE6 +
  • Support to dynamically adjust icon size, color and so on according to the font

disadvantage

  • Multi-color ICONS are not supported
  • Browser fonts render slightly differently on different devices. Text is rendered differently on different browsers or systems. The position and size of the text displayed may be affected by CSS properties such as font-size, line-height, word-spacing, and so on, which can be difficult to adjust

Usage: Step 1: Introduce custom font ‘font-face’

 @font-face {
   font-family: "iconfont";
   src: url('iconfont.eot'); /* IE9*/
   src: url('iconfont.eot#iefix') format('embedded-opentype'), /* IE6-IE8 */
   url('iconfont.woff') format('woff'), /* chrome, firefox */
   url('iconfont.ttf') format('truetype'), /* Chrome, Firefox, Opera, Safari, Android, iOS 4.2+*/'iconfont.svg#iconfont') format('svg'); /* iOS 4.1- */}Copy the code

Step 2: Define styles that use iconfont

.iconfont {
  font-family:"iconfont"! important; font-size:16px; font-style:normal; -webkit-font-smoothing: antialiased; - its - text - stroke - width: 0.2 px; -moz-osx-font-smoothing: grayscale; }Copy the code

Step 3: Select the icon and get the font code and apply it to the page

<i class="iconfont"> &#xe604; 
Copy the code

Effect:

The basic idea is to use @font-face to introduce a custom font (which is actually a font library), which specifies that  should look like a penguin. In fact, similar to ‘flower shorts’, they look different in different font Settings.

However, its disadvantages are obvious, unicode writing is not intuitive, meaning is not clear. See light & # xe604; This Unicode you have no idea what it stands for. And that’s where we have the font-family class.

font-class

Compared with Unicode, it has the following characteristics:

  • Good compatibility, support ie8+
  • Compared to Unicode semantics, writing is more intuitive. It’s easy to tell what the icon is.

Step 1: Copy the fontClass code generated below the project:

../font_8d5l8fzk5b87iudi.css
Copy the code

Step 2: Select the corresponding icon and get the class name, and apply it to the page:

<i class="iconfont icon-xxx"></i>
Copy the code

Effect:

The main principle is the same as Unicode, it just goes the extra step of writing.icon-qq instead of . It writes Unicode in the before property of each class, so it doesn’t have to write unicode. For example.icon-qq :before {content: “\e604”; }

Compared to Unicode, it is more convenient and intuitive to modify. But there is also a big hole in a project. The author used two groups of font-size classes in a project, because he did not do a good job in the namespace, all the classes were placed in the. Iconfont namespace, which caused a variety of avalanche of problems, the modification of a long time, so use of font class must pay attention to the namespace problem.

symbol

With the demise of the evil browser, the SVG-icon usage form is slowly becoming the mainstream and recommended approach. For related articles, please refer to Zhang Xinxu’s article “Future Will Be Hot: Introduction to SVG Sprite technology”

  • Multi-color ICONS are no longer limited by monochrome.
  • Support for style adjustment by font size and color as in fonts.
  • Support ie 9 +
  • Use CSS to achieve animation.
  • Reduce HTTP requests.
  • Vector, scaling without distortion
  • You can control every part of an SVG icon very finely

Step 1: Copy the generated symbol code below the project:

Introduction. / iconfont. JsCopy the code

Step 2: Add generic CSS code (just once) :

<style type="text/css"> .icon { width: 1em; height: 1em; Vertical - align: 0.15 em. fill: currentColor; overflow: hidden; } </style>Copy the code

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>
Copy the code

Are the benefits of using SVG icon – I don’t have to send woff | eot | the vera.ttf | these many font library request, I all SVG can inline within the HTML.

Inline SVG vs Icon Fonts
svg
icon-font
SVG Sprite
<use xlink:href="#icon-QQ" x="50" y="50" />
Future Hot: An introduction to SVG Sprite technology
SVG Sprite

Create the icon-Component component

Now that we have the icon, the next step is how to use it elegantly in your own projects. The rest of the code is based on vue instances (ps: React is also simple, the principle is similar).

//components/Icon-svg
<template>
  <svg class="svg-icon" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<script>
export default {
  name: 'icon-svg'.props: {
    iconClass: {
      type: String.required: true}},computed: {
    iconName() {
      return `#icon-The ${this.iconClass}`}}}</script>

<style>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15 em;
  fill: currentColor;
  overflow: hidden;
}
</style>


Copy the code
// Introduce the SVG component
import IconSvg from '@/components/IconSvg'

// Register icon-svg globally
Vue.component('icon-svg', IconSvg)

// Use in code
<icon-svg icon-class="password" />
Copy the code

By simply encapsulating an Icon-SVG component, we can use ICONS in our vUE projects in a simple and elegant way.

Further transformation

But as a good front-end development, how can this be satisfied! Currently, there is a fatal drawback: all svG-Sprites are generated using iconfont’s iconfont. Js.

  • First, it is a section of JAVASCRIPT to generate SVG code, all the ICONS are not intuitive.

  • Second, it can’tAccording to the need to loadCannot be dynamically generated based on which SVG we usesvg-sprite.
  • Customization is poor, and exported SVG usually contains a lot of useless information, such as editor source information, comments, and so on. Usually contains other content that does not affect the render or can be removed.
  • Add unfriendlinessIf I have some custom SVG ICONS, how do I compare with the original onesiconfontPut it all together? You can only upload it nowiconfontIt is tedious to put the original icon in a project library and download it again later.

Using SVG – Sprite

The next step is to make our own SVG-Sprite. The SVG sprite-Loader is a Webpack loader that can be used to package multiple SVGS into SVG-Sprites.

Let’s introduce how to transform vue-CLI and add SVG-Sprite-Loader.

We noticed that vue-CLI by default uses a URl-loader to process SVG in the /img directory, so the introduction of SVG-sprite-loader caused some conflicts.

// By default, 'vue-cli' is used to process SVG files. If the match is successful, use url-loader to process the files.
 {
    test: /\.(png|jpe? g|gif|svg)(\? . *)? $/.loader: 'url-loader'.options: {
      limit: 10000.name: utils.assetsPath('img/[name].[hash:7].[ext]')}}Copy the code

There are two solutions. The simplest is that you can remove the SVG from test so that you don’t have to deal with the SVG, which of course is very unfriendly.

  • You can’t guarantee that all of your SVG will be used as ICONS, and some may indeed be used only as image resources.
  • There is no guarantee that some of the third-party libraries you use will use SVG.

So the safest and most reasonable thing to do is to exclude and include webPack, and have the SVG-sprite-Loader handle only the SVG in the folder you specify, and the URL -loaer handle only the SVG outside the folder. This is the perfect solution to the previous conflict. The following code

That’s all you need to do, just fill in the class name once SVG is introduced

import '@/src/icons/qq.svg; < span style =" box-sizing: border-box; color: RGB (50, 50, 50); line-height: 20px; font-size: 14px! Important; white-space: normal;Copy the code

This alone is still very inelegant. If there are 100 ICONS in my project, should I manually introduce them one by one? Lazy is programmer’s first productivity!!

Automatic import

First we create a folder for our ICONS such as @/ SRC/ICONS and put all the ICONS in this folder. Then we use webPack’s require.context. Many of you may be unfamiliar with require.context

require.context(“./test”, false, /.test.js$/); This line of code will go under the test folder (no subdirectories) and find all files whose names end in.test.js that can be required. To put it more bluntly, we can import the corresponding file module through regular match.

Require. context takes three arguments:

  • Directory: indicates the directory to be searched
  • UseSubdirectories: Whether to search subdirectories
  • RegExp: matches the regular expression of the file

And with that in mind, we can write this to automatically introduce all the ICONS under @/ SRC/ICONS

const requireAll = requireContext= > requireContext.keys().map(requireContext)
const req = require.context('./svg'.false, /\.svg$/)
requireAll(req)
Copy the code

After that, we can add, delete and change the icon directly to the corresponding icon in the folder, and do nothing to generate the SVG symbol automatically.

Further optimize your SVG

First let’s take a look at what an SVG export from aliiconFont looks like.

Sure, iconFont’s SVG content is pretty streamlined, but you’ll find that it’s still a lot of useless information, creating unnecessary redundancy. This is true even of the SVG exported by Iconfont, let alone (possibly) by a less technical designer who cares more about the beauty of the UI. Fortunately, THE SVG-Sprite-Loader also takes this into account and currently only retrieves the contents of the PATH in SVG and nothing else. Generate SVG as shown below:

But any redundant information that you generate in the path it’s not going to process. Like comments or something

This is where we use another nice thing to do — SvGo

SVG files, especially exported from various editors, usually contain a lot of redundant and useless information such as editor metadata, comments, hidden elements, default or non-optimal values and other stuff that can be safely removed or converted without affecting SVG rendering result.

It supports dozens of optimizations, very powerful, 8K + Star is enough to show the problem.

Detailed operation can refer to the official document Zhang Xinxu big article (it is the big article, maybe this is the big guy!) I won’t go into this article.

Write in the last

The above outline illustrates the evolution of icon use in front-end projects. Generally speaking, the right one is the best. Take the choice of Vue React versus Angular, personally, I think each framework has its own characteristics and applicable business scenarios, so any recommendation and discussion that does not combine business scenarios are blind. As mentioned above, there are about five usage scenarios of front-end icon. The first one, Font Awesome, is not used because it is bad, but it is not suitable for business scenarios. If your team does not have a special designer or the customization of icon is not high, you can use it. Font Awesome Github has more than 50,000 stars, a sign of community recognition. For example, if your project has high adaptation requirements for low-end browsers and you want to force SVG as an icon, you are really doing yourself a disservice. Therefore, all the solutions are not absolutely good or bad, suitable for their own business scenarios, to solve their actual pain points, improve their own development efficiency of the solution is a good solution.

Of the pit

A complete instance of the techniques covered in this article can be found in vue-element-admin. Vue-element-admin has also released a new version and the accompanying Chinese document (the document really writes I want to spout blood). Whether to use this project or not, it is recommended to have a look, should be able to help you write the vUE project. Welcome to use and raise deficiencies. The main personal free circle.

Series of articles:

  • Hand touch hand, take you with Vue backstage Series one (Basic)
  • Hand touch hand, take you with vue wanbackstage series 2 (login permission)
  • Hand touch hand, take you with VUE backstage series three (actual combat)
  • Hand touch hand, take you with vue luai background series 4 (vueAdmin a minimalist background foundation template)
  • Hand touch hand, take you with VUE Backstage Series 5 (v4.0 new version)
  • Hand to hand, take you to encapsulate a Vue Component
  • Hand to hand, take your elegant use of icon
  • Hand to hand, take you to use reasonable posture webPack4 (1)
  • Hand to hand, with a reasonable posture to use WebPack4 (2)