When designing and developing user interfaces, we often encounter problems related to fonts:

  • The default system font varies with terminal devices.
  • The same font downloaded on different platforms can be rendered slightly differently on the same device.
  • Designers often use special fonts in their designs for certain scenes or when they need to be clearly distinguished from other content.

For the first two points, we can use some open source fonts that are supported by default in the development language, or depending on the company, we can choose a commercial font that has purchased the copyright and download the specified font package to reference in the project.

For the third point, sometimes only numbers or letters need special fonts, and sometimes only a few Chinese characters need special fonts. At this time, facing less than a few megabytes, more than tens of megabytes of font packages, blind introduction is not desirable.

The content of a particular font is known

You can directly use picture method, common scenarios: Banner, KV, button, etc. However, if there are many such scenarios in the project, it is recommended to introduce a custom font package (see the method below).

The content of the particular font is unknown and contains Chinese characters

In this case, I do not know a perfect solution for dynamic content customization font package, but usually directly introduce the whole font package

Special font has unknown content but does not contain Chinese characters (also applies if it contains fixed Chinese characters)

Font spider cli, the command-line version of font spider, is recommended. Personally, I find it easier to use the CLI version than spider, and I don’t need any additional KNOWLEDGE of HTML and CSS.

The steps are as follows:

Create a new folder that can be found anywhere. But if it is in your project, it is recommended to delete after use.

$ mkdir font-spider-cli && cd font-spider-cli

Install the cli

$ npm install font-spider-cli

Follow the documentation on NPM to try it out

Enter the text to be converted in the FSC -t command. -f Name of the text file without the suffix -n name

Here are some things to note:

  • Font package files do not have type suffixes
  • Drag the font package file directly into the terminal window to display the full path. If the font package name contains Spaces, delete them
  • Otherwise, we should get an error because we don’t have onefscEnvironment variables of

FSC - t you want to convert the content of the -f/Users/myMac/Desktop/font - spiders - cli/MesloLGS -n myFont

Sure enough, ZSH: Command not found: FSC. In order to facilitate the author, a one-time tool, no longer configure environment variables, direct index to the script file directory execution

Node_modules/font - spiders - cli/bin/FSC - t you want to convert the content of the -f/Users/myMac/Desktop/font - spiders - cli/MesloLGS -n myFont

Then you will see:

Font family: myFont Original size: 1260.156 KB // Include chars: ABCDEFG chars length: 7 Font id: ecc0892b0b3890d20437f3285bf9fe94 CSS selectors: .text Font files: File MesloLGS.eot created: Woff created: 7.6KB File meslolgs.svg created: 7.6kb File meslolgs.svg created: 7.6kb File meslolgs.svg created: 7.6kb File meslolgs.svg created: The top four lines are the font package size after extracting the specified contentCopy the code

Ttf.eot.svg. Woff and the.spider folder containing the original font package.

A look at the source code, in fact, the CLI version is the font spider needs to do some manual operations to encapsulate in, more quickly.

Paste the core:

const program = require('commander');
const version = require('./package.json').version;
const fontspider = require('font-spider');
const colors = require('colors/safe');
const fs = require('fs-extra');
const spider = fontspider.spider;
const compressor = fontspider.compressor;
const path = require('path');
program
    .version(version)
    .option('-t, --text <text>'.'Enter the text to be converted')
    .option('-f, --font <font>'.'Enter font address (execute directory)')
    .option('-n, --name <name>'.'Enter font address (execute directory)')
    .parse(process.argv);

function mock(text, font, fontname) {
    font = path.resolve(process.cwd(), font);
    return `
    <style>
    @font-face {
        font-family: '${fontname}';
        src: url('${font}.eot');
        src:
          url('${font}.eot? #font-spider') format('embedded-opentype'), url('${font}.woff') format('woff'),
          url('${font}.ttf') format('truetype'),
          url('${font}.svg') format('svg');
        font-weight: normal;
        font-style: normal;
      }
    .text {
        font-family: '${fontname}';
    }
    </style>
    <div class="text">${text}</div>
    `;
}

if (
    typeof program.text === 'function' ||
    typeof program.font === 'function' ||
    typeof program.name === 'function')
{
    onerror(new ReferenceError('-t or -f or -n not entered '));
}

const html = mock(program.text, program.font, program.name);

compressWebFont([{
    path: process.cwd(),
    contents: html
}], {});

function compressWebFont(htmlFiles, options) {

    logIn('Loading .. ');

    spider(htmlFiles, options).then(function(webFonts) {

        if (webFonts.length === 0) {
            clearLonIn();
            log('<web font not found>');
            return webFonts;
        }

        logIn('Loading ... ');

        return compressor(webFonts, options);
    }).then(function(webFonts) {

        clearLonIn();
        webFonts.forEach(function(webFont) {

            log('Font family:', colors.green(webFont.family));
            log('Original size:', colors.green(webFont.originalSize / 1000 + ' KB'));
            log('Include chars:', webFont.chars);
            log('Chars length:', colors.green(webFont.chars.length));
            log('Font id:', webFont.id);
            log('CSS selectors:', webFont.selectors.join(', '));
            log('Font files:');

            webFont.files.forEach(function(file) {
                if (fs.existsSync(file.url)) {
                    log('File', colors.cyan(path.relative('/', file.url)),
                        'created:', colors.green(file.size / 1000 + ' KB'));
                } else {
                    log(colors.red('File ' + path.relative('/', file.url) + ' not created')); }}); log(' ');
        });

        return webFonts;
    }).catch(onerror);
}
Copy the code