首页 > 解决方案 > 如何在 vuejs 和 webpack 中加载字体文件?

问题描述

我做了很多阅读,但没有一个链接确切地告诉我如何在 vuejs 中添加字体。这就是我在less文件中导入字体的方式。

@font-face {
  font-family: "Questrial";
  src: url("../../fonts/Questrial-Regular.ttf");
}

@font-face {
  font-family: "Galano_Grotesque_extra_Bold";
  src: url("../../fonts/Galano_Grotesque_Bold.otf");
}

@font-face {
  font-family: "Galano_Grotesque_Bold";
  src: url("../../fonts/Galano_Grotesque_DEMO_Bold.otf");
}

这是我得到的错误

./src/themes/jatango-theme/components/fonts/Galano_Grotesque_Bold.otf 中的错误 1:4 模块解析失败:意外字符 '' (1:4) 您可能需要适当的加载程序来处理此文件类型。(此二进制文件省略了源代码)

我是 VUEJS 的新手,以前没有反应或角度的知识。我只知道 jquery 和 javascript。所以请有人给我一个包含字体的分步指南。提前致谢 :)

文件夹结构

文件夹结构

标签: javascriptvue.jswebpackvuejs2less

解决方案


将字体放入public/fonts/文件夹中。在 css 或 scss 中,指定以 . 开头的路径/fonts/

示例scss:

$font-dir: "/fonts/";

@font-face {
  font-family: "NameFont";
  src: url("#{$font-dir}NameFontRegular/NameFontRegular.eot");
  src: url("#{$font-dir}NameFontRegular/NameFontRegular.eot?#iefix")format("embedded-opentype"),
  url("#{$font-dir}NameFontRegular/NameFontRegular.woff") format("woff"),
  url("#{$font-dir}NameFontRegular/NameFontRegular.ttf") format("truetype");
  font-style: normal;
  font-weight: normal;
}

接下来,将你的 scss 导入 main.js

例子:

// eslint-disable-next-line
import styles from './assets/scss/main.scss';

或在vue.config.js

例子:

module.exports = {
...
  css: {
    modules: true,
    loaderOptions: {
      css: {
        localIdentName: '[name]-[hash]',
        camelCase: 'only'
      },
      sass: {
        data: '@import "~@/assets/scss/import/_variables.scss"; @import "~@/assets/scss/import/_mixins.scss";'
      },
    },
  },
...
}

推荐阅读