如何在 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。所以请有人给我一个包含字体的分步指南。提前致谢 :)

文件夹结构

文件夹结构

原文由 Raj 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 674
2 个回答

希望这会帮助其他面临同样问题的人。出于某种原因,Vue.js 在使用 .otf 文件时出错。我使用 .woff 现在一切正常。在您的 webpack.config.js 文件中使用以下代码:

       module.exports = function (config, { isClient, isDev }) {
            module: { rules: [ { test: /\.(woff|woff2|eot|ttf|svg)(\?.*$|$)/,
            loader: 'file-loader' } ] }
            return config }

并使用类似这样的方法将文件导入到您的 css 文件中

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

原文由 Boussadjra Brahim 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

例子:

 $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";'
      },
    },
  },
...
}

原文由 Pavel Levin 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进