如何在 vuejs 和 webpack 中加载字体文件?

How to load a font file in vuejs and webpack?

我读了很多书,但是 none 的链接向我展示了如何在 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");
}

这是我得到的错误

ERROR in ./src/themes/jatango-theme/components/fonts/Galano_Grotesque_Bold.otf 1:4 Module parse failed: Unexpected character '' (1:4) You may need an appropriate loader to handle this file type. (Source code omitted for this binary file)

我是 VUEJS 的新手,之前对 React 或 angular 一无所知。 我只知道jquery和javascript。所以请有人给我一个包含字体的分步指南。提前致谢:)

这是一个 webpack 错误。您缺少 webpack loader to manage font files. Usually I use file-loader 字体:

{
  test: /\.(ttf|otf|eot|woff|woff2)$/,
  use: {
    loader: "file-loader",
    options: {
      name: "fonts/[name].[ext]",
    },
  },
}

将此代码添加到您的 webpack config file (module > rules section) or if you're using vue-cli 3, in your vue.config.js 文件(configurewebpack 部分)。

希望这对面临同样问题的其他人有所帮助。由于某些原因 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"); 
   }

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

开头的路径

例子css:

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