Preface
In the WeChat applet, we set the font of the text through the font-family CSS property in the wxss file, and the WeChat applet has built-in fonts that it supports. You can check the fonts supported by the WeChat applet through code prompts:
Please refer to the specific styles of these fonts:
In actual development, our UI designers may use a variety of fonts when drawing prototypes. These fonts are not built-in fonts in WeChat mini programs. Next, we will explain in detail how to use these fonts in WeChat mini programs. ;
1. Font import process
The WeChat applet provides developers with a dedicated API for importing external fonts:wx.loadFontFace
Its official documentation is as follows:
wx.loadFontFace(Object object) | WeChat Open Document
You can refer to the above documents for specific usage specifications. Next, we will focus on several issues that need attention:
- Specify the font file resource through the source parameter, which can be a local resource or a network resource. In this example, network resources are used; if it is a network resource, the font link must be https, not http, otherwise the font resource cannot be imported normally ;
- The WeChat applet has restrictions on the font formats it supports, but this is not clearly stated in the document. According to actual testing,
ttf|ttc|otf
common font formats such as- The font link must be from the same origin, or cors support must be enabled; the so-called cors refers to cross-domain resource sharing, which means that if the mini program and the server storing the font link are not from the same origin, cors support needs to be enabled so that the mini program can Access the server normally and obtain the font resources; in this example, the font resources are deployed through nginx and just add cors support (will be discussed in detail later)
After clarifying the precautions, let's take a look at the specific import method (because there are many font files that need to be imported, batch import is performed in app.js):
Take app.js
importing in a file DIN_Alternate_Bold.ttf
as an example:
App({
data: {
},
getFonts(name) //导入外部字体
{
let url = "yourURL" //自己服务器的域名(或IP)
let source = 'url(' + url + name + ')'
console.log(source)
wx.loadFontFace({
family: name.substring(0, name.length - 4), //名称去掉后缀
source: source,
global: true,
success(res) {
console.log("load " + name.substring(0, name.length - 4) + " success")
// console.log(res)
},
fail(res) {
console.log("load " + name.substring(0, name.length - 4) + " failed")
console.log(res) //出错则打印信息
}
})
},
onLaunch() {
console.log('app.js载入')
this.getFonts('DIN_Alternate_Bold.ttf')
},
globalData: {
}
})
We getFonts
called the official API through the method to import the external font file, and then onLaunch
called the method in to load the external font resource when app.js is loaded;
wx.loadFontFace
A brief explanation of the parameters in :
family
: Customized font name (the name here is completely customized, but it must be consistent with the name used in wxss)source
: The address of the font resource; format:url(https://yourURL/DIN_Alternate_Bold.ttf)
global
: Whether the font takes effect globally, because we import it in app.js, we need to set it to take effect globally, otherwise the font style imported here cannot be used in the wxss file of each page.success/fail
: Callback function for success/failure of font resource import, which can print some prompt information
After the font resource is imported successfully, we can use it in the wxss file. The example is as follows:
In app.wxss
:
.DIN_Alternate_Bold{
font-family: 'DIN_Alternate_Bold';
}
Here DIN_Alternate_Bold
is the font name customized in the above js code (by setting family)
In this case, which part of the text needs to be set to DIN_Alternate_Bold
the font style, you only need class = "DIN_Alternate_Bold"
to do it, which is more convenient.
2. Font resource deployment
As explained in the above notes, we need to deploy the font resources to the nginx server and enable cros support, and they must be accessible through https. Next, we will gradually solve these problems;
2.1 Server preparation
In this example, Huawei Cloud ECS server is used (the operating system is ubuntu), security group rules are configured, and port 80 (the default port of nginx) is opened.
It should be noted that if the WeChat applet needs to be online, the server used must have a public IP; if it is only used for local learning and testing, a virtual machine can be used;
2.2nginx installation
2.2.1 nginx download
Visit the official website: nginx: download
Find the version you want to download:
It is recommended that the version is not too low. In this example, 1.20.2 is used.
After the download is completed, transfer it to the server and tar zxvf nginx-1.20.2.tar.gz -C /opt/
decompress it through the command.
nginx-1.20.2.tar.gz is the name of the compressed package; /opt/ is the decompression path, which can be customized
2.2.2 nginx installation
First enter the decompression directory of nginx:
Then configure ssl:
Execution instructions:./configure --prefix=/usr/local/nginx --with-http_ssl_module
./configure is to configure nginx; --prefix is the installation path of nginx; --with-http_ssl_module enables SSL support on the surface;
Next compile and install:
Execution instructions:make && make install
Then wait for the compilation and installation to complete;
After the installation is complete, enter the installation path /usr/local/nginx
and check the nginx version to install the module:sbin/nginx -V
2.2.3 nginx startup/shutdown
The instructions for starting and stopping nginx are all in the sbin folder:
- nginx starts:
sbin/nginx
After the startup is complete, ps -ef | grep nginx
check whether the startup is successful:
As shown above, the startup is successful;
You can also netstat -anp | grep 80
view it via:
- nginx shutdown:
sbin/nginx -s stop
Precautions:
- If nginx cannot be started and stopped normally, and if an error occurs when starting, the port is occupied, you can
netstat -anp | grep 80
check whether port 80 is occupied. If so, just end the process (kill -9 PID
);- If the process has ended after ending
nginx:master
, but it appears , and after killing a process, a worker process will be automatically started, and the specific performance is that the process number is extended; this indicates that a zombie processnginx:worker
has appeared, and the process cannot be ended by simply killing it. You need to use , kill Kill all processes related to nginx;kill -9
killall -9 nginx
2.2.4 nginx usage
After the installation and deployment is completed, you can access nginx by typing in the browser http://你的服务器ip/
:
If it cannot be accessed, first consider whether security group rules are configured and port 80 is open (cloud server)
Then consider the firewall settings. If you cannot access the browser because the firewall is turned on, you can consider turning off the firewall first:
- Turn on the firewall:
systemctl start firewalld.service
- Check the firewall status:
systemctl status firewalld.service
- Turn off the firewall:
systemctl stop firewalld.service
If the problem cannot be solved, you can consider re-deploying and installing nginx, because it may be caused by nginx being passed yum
or apt
installed on the server before. Before re-installing and deploying, you can find / -name nginx
find all nginx-related files on the server and delete them one by one. Redeploy (note, when deleting, be sure to understand the function of this file to avoid accidentally deleting it)
2.2.5 nginx configuration file
Path: /usr/local/nginx/conf/nginx.conf
, the default configuration is http server;
Set the default page to open:
Set the page that appears when the status code is 500, 502, 503, 504
Other configurations will be introduced in detail below;
2.3 Configure ssl certificate
First we need to apply for an SSL certificate and bind it to the domain name
For certificate application, please refer to: 2022 Alibaba Cloud free SSL certificate application process (detailed pictures and texts) - Alibaba Cloud Developer Community
Just search the document for domain name binding and set it up by yourself;
After applying for the SSL certificate, we can download .key
and .pem
two files for nginx configuration:
then open /usr/local/nginx/conf/nginx.conf
the file
First, without modifying the default configuration file, locate the http server:
Add an https server outside the server with the following content:
server{
listen 443 ssl; #端口号
server_name yourURL; #服务器 (域名或ip 示例:localhost)
ssl_certificate /opt/certs/gongzai.xyz.pem; # .pem文件
ssl_certificate_key /opt/certs/gongzai.xyz.key; # .key文件
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_protocols TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# 配置字体资源的访问路径
location ~ .*\.(ttf|otf|ttc|TTF)$ {
root /usr/local/nginx/html/ttfs;
expires 10d;
}
}
In the above content, except for the notes that need to be adjusted according to the actual situation, the remaining parameters can be fixed;
Explain the following code
# 配置字体资源的访问路径
location ~ .*\.(ttf|otf|ttc|TTF)$ {
root /usr/local/nginx/html/ttfs;
expires 10d;
}
ttf|otf|ttc|TTF
is the file resource suffix; /usr/local/nginx/html/ttfs
is the storage path of the font resource;
This configuration shows that if you want to access the font resources on the nginx server, go to the corresponding path to find the corresponding resources;
After configuring the https server, go back to the http server and delete the contents, leaving only:
server {
listen 80; # 默认端口号
server_name yourURL; #服务器 (域名或ip 示例:localhost)
rewrite ^(.*)$ https://$host$1 permanent; #将http请求转发为https请求
}
Now that the SSL certificate is configured, just restart the nginx server;
If you want to access font resources later, you can download them by typing in the browser https://yourURL/字体资源名称
. The access method is the same in the WeChat applet.
2.4 Turn on cros support
Open the nginx configuration file nginx.conf
:
Just add it in location add_header Access-Control-Allow-Origin *;
, as follows:
location ~ .*\.(ttf|otf|ttc|TTF)$ {
add_header Access-Control-Allow-Origin *;
root /usr/local/nginx/html/ttfs;
expires 10d;
}
The meaning of this line of code is to add a header field named " Access-Control-Allow-Origin " to the HTTP response and set its value to "*". The purpose of this header field is to specify the permissions to access the resource. Origin, that is, which domain names can make cross-domain requests with the server;
When the browser sends a cross-domain request to the server, the server returns the value of this header field as part of the response header. By setting the value of this field to "*", it means that requests from any domain name are allowed to be responded to . In other words, the server allows front-end applications from any domain name to obtain resources through methods such as AJAX, Fetch API, etc.
Therefore, through such settings, our applet can obtain font resources normally (otherwise, real machine debugging will not be able to load font resources)
postscript
If an error is reported in WeChat developer tools:
You can ignore it. The official documentation also states that this error will not affect the normal import of font files;
In addition, if the font file is relatively large (more than 10M), or there are many font resources that need to be imported, you can consider setting up a resource loading interface and wait until all resources are loaded before entering the mini program to avoid problems such as lagging;
The nginx deployment font resource introduced in this article and requesting it through https is the simplest way. The author's ability is limited. If you need optimization, please find the information yourself.
If there are any mistakes in the article, please correct me! If you encounter other questions, please feel free to discuss and communicate in the comment area!