webpack 设置字体 不生效

跟着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')
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值