可以通过webpack的file-loader或url-loader来将ttf文件打包并缓存到项目中。

  1. 安装file-loader或url-loader
npm install --save-dev file-loader

npm install --save-dev url-loader
  1. 在webpack配置文件中添加loader配置
module: {
  rules: [
    {
      test: /\.(woff|woff2|eot|ttf|otf)$/,
      use: [
        {
          loader: 'file-loader', // 或者 'url-loader'
          options: {
            name: '[name].[ext]',
            outputPath: 'fonts/'
          }
        }
      ]
    }
  ]
}
  1. 在Vue组件中引入ttf文件
<template>
  <div class="font-example">
    <h1>Hello World</h1>
  </div>
</template>

<script>
import '@/assets/fonts/Example.ttf'

export default {
  name: 'FontExample'
}
</script>

<style scoped>
@font-face {
  font-family: 'Example';
  src: url('~@/assets/fonts/Example.ttf') format('truetype');
}

h1 {
  font-family: 'Example';
}
</style>

这样就可以在项目中缓存ttf文件并使用它们了。注意,如果使用了url-loader,还可以通过配置options中的limit参数来控制小于多少字节的文件才会被转化为base64编码

如何在vue项目中缓存ttf文件

原文地址: https://www.cveoy.top/t/topic/g8nV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录