在vue-cli 3中如何使用本地字体?

7

我想在我的vue-cli 3项目中导入本地字体。

.woff和.woff3文件位于src/assets/typo,并且我在src/scss/_typo.scss中包含它们: enter image description here

我的 _typo.scss看起来像这样:

@font-face {
  font-family: 'HKGrotesk';
  src:  url('@/assets/typo/HKGrotesk-Bold.woff2') format('woff2'),
        url('@/assets/typo/HKGrotesk-Bold.woff') format('woff');
  font-weight: bold;
  font-style: normal;
}

@font-face {
  font-family: 'HKGrotesk';
  src:  url('@/assets/typo/HKGrotesk-Medium.woff2') format('woff2'),
        url('@/assets/typo/HKGrotesk-Medium.woff') format('woff');
  font-weight: medium;
  font-style: normal;
}

@font-face {
  font-family: 'HKGrotesk';
  src:  url('@/assets/typo/HKGrotesk-Regular.woff2') format('woff2'),
        url('@/assets/typo/HKGrotesk-Regular.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

这是我的vue.config文件,用于在全局范围内使用颜色和字体:
module.exports = {
  css: {
    loaderOptions: {
      sass: {
        data: `
          @import "@/scss/_colors.scss";
          @import "@/scss/_typo.scss";
        `
      }
    }
  }
};

当我运行我的项目时,我收到了以下错误信息:
Failed to compile.

./src/App.vue?vue&type=style&index=0&lang=scss& (./node_modules/css-loader??ref--8-oneOf-1-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/lib??ref--8-oneOf-1-2!./node_modules/sass-loader/lib/loader.js??ref--8-oneOf-1-3!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/App.vue?vue&type=style&index=0&lang=scss&)
Module not found: Error: Can't resolve './@/assets/typo/HKGrotesk-Bold.woff' in '/Users/robin/Documents/Code/2018/iamrobin-portfolio/src'

1
你搞定这个问题了吗?我已经到处寻找答案,但无法使其工作。对我而言,在我的URL中使用直接的'/assets/typo/font.woff'路径。它编译了,但在浏览器中没有显示出来。 - tettoffensive
1
'/assets/typo/...' 无法正常工作的原因是它找不到文件。这些文件需要相对于 scss 文件。Webpack 将根据其运行方式(开发或编译)替换为正确的资源文件。 - Daniel
4个回答

4

不确定这个阶段是否有所帮助,但我遇到过同样的问题,并通过使用相对路径(即../assets/fonts/myfont.woff)而不是使用根通配符(即@/assets/fonts/myfont.woff@~/assets/fonts/myfont.woff)来解决它。

希望能帮到您!


4
如果我使用相对路径像'../assets/font/myfont.woff',会出现模块错误,找不到文件。如果我只使用'/assets/fonts/myfont.woff',编译可以通过,但在浏览器中字体无法显示。 - tettoffensive

2

试一试这个~@/assets/...

@font-face {
  font-family: 'HKGrotesk';
  src:  url('~@/assets/typo/HKGrotesk-Regular.woff2') format('woff2'),
        url('~@/assets/typo/HKGrotesk-Regular.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

0

我一直遇到同样的问题,希望在vue cli的github问题中有相关引用 :) 通过强制使用相对路径来解决,但这真的很糟糕。


0
使用 vue-cli 3,您已经拥有 Webpack 4 和默认的加载程序,因此您不需要为此任务配置任何加载程序。您唯一需要做的是在您的 scss 文件夹中创建一个 main.scss 文件。在那个文件中,导入您的 _color.scss 和 _typo.scss。然后,在您的 main.js 中像 import './stylus/main.scss'; 这样导入您的主要样式文件。通过这样做,您应该就可以开始了。只需在您的 css 中使用您的字体,例如 body {font-family: "HKGrotesk", sans-serif;}。不要忘记从 vue.config 中删除您的 css 加载程序,以避免干扰 webpack 的默认行为。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接