跟着webpack官方文档学习,在【加载 fonts 字体】 这一板块遇到了问题,就是加载的字体不生效
1.项目代码
- 项目结构
webpack-demo
|- package.json
|- webpack.config.js
|- /dist
|- bundle.js
|- index.html
|- /src
|- MontserratAlternates-Regular.otf
|- style.css
|- index.js
|- /node_modules
- webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
],
},
};
- src/style.css
(错误代码)
@font-face {
font-family: 'MontserratAlternates';
/*src: url('./MontserratAlternates-Regular.otf') format('otf');*//*错误代码*/
src: url('./MontserratAlternates-Regular.otf') format('truetype');/*正确代码*/
font-weight: normal;
font-style: normal;
}
.hello{
color: red;
font-family: 'MontserratAlternates';
font-weight:normal;
}
- 运行
npm run build
的结果:不报错,也引用了字体文件,但字体不生效
2. 分析代码
- 分析:经过百度,查找分析到,是css代码中@font-face中引用字体文件时写错了,不同的font文件后缀,format标准不同
- 标准:阿里巴巴矢量图标库iconfont的书写标准如下:
@font-face {
font-family: "iconfont logo";
src: url('https://at.alicdn.com/t/font_985780_km7mi63cihi.eot?t=1545807318834');
src: url('https://at.alicdn.com/t/font_985780_km7mi63cihi.eot?t=1545807318834#iefix') format('embedded-opentype'),
url('https://at.alicdn.com/t/font_985780_km7mi63cihi.woff?t=1545807318834') format('woff'),
url('https://at.alicdn.com/t/font_985780_km7mi63cihi.ttf?t=1545807318834') format('truetype'),
url('https://at.alicdn.com/t/font_985780_km7mi63cihi.svg?t=1545807318834#iconfont') format('svg');
}
- 规则:font文件后缀集齐对应的format
woff -> format('woff')
woff2 -> format('woff2')
eot -> 不写format | format('embedded-opentype')
ttf -> format('truetype')
otf -> format('truetype')
svg -> format('svg')