面试题答案
一键面试开发环境优化
在开发环境中,注重调试便捷性。可以保留字体文件的原始格式,便于快速定位和修改问题。
- Webpack配置:
module.exports = {
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
],
},
};
这里使用asset/resource
类型,它会将字体文件原封不动地输出到指定目录,保持其原始格式,方便调试。
生产环境优化
在生产环境中,注重极致性能。可以对字体文件进行压缩,减少文件体积,同时采用合适的加载策略。
- 字体压缩:
- 安装
terser-webpack-plugin
用于压缩字体文件(虽然主要用于JavaScript压缩,但对一些字体格式也有压缩效果)。 - 使用
image-webpack-loader
对字体进行优化(它也支持对字体文件进行优化)。 - 安装相关插件:
- 安装
npm install terser-webpack-plugin image-webpack-loader --save-dev
- Webpack配置:
const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');
module.exports = {
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
use: [
{
loader: 'image-webpack-loader',
options: {
mozjpeg: {
progressive: true,
quality: 65,
},
// optipng.enabled: false will disable optipng
optipng: {
enabled: false,
},
pngquant: {
quality: [0.65, 0.90],
speed: 4,
},
gifsicle: {
interlaced: false,
},
// the webp option will enable WEBP
webp: {
quality: 75,
},
},
},
],
},
],
},
optimization: {
minimizer: [
new TerserPlugin({
parallel: true,
terserOptions: {
compress: {
drop_console: true,
},
},
}),
],
},
};
这里通过image-webpack-loader
对字体文件进行优化,并且使用TerserPlugin
进一步压缩(包括可能对字体文件中的可压缩部分进行处理)。同时,还可以结合webpack - bundle - analyzer
插件分析字体文件在打包后的体积占比,以便进一步优化。
另外,在生产环境还可以考虑字体的加载策略,比如使用font - loading
相关技术,如font-display
属性来控制字体何时显示,避免FOUT(Flash of Unstyled Text)或FOIT(Flash of Invisible Text)问题。可以在CSS中设置:
@font - face {
font - family: 'YourFontFamily';
src: url('/path/to/yourfont.woff2') format('woff2'),
url('/path/to/yourfont.woff') format('woff');
font - display: swap;
}
font - display: swap
会让浏览器尽快显示文本,在字体加载完成后再替换成自定义字体,提升用户体验。