首页 > 解决方案 > 如何使用 Parcel 从@font-face 加载字体?

问题描述

我正在使用 Parcel 进行捆绑,我想在我的项目中包含自定义字体

在我的 SCSS

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

然后我在这样的地方使用它
font-family: 'Storytella', serif;

包.json

{
  "name": "pr",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "normalize.css": "^8.0.1",
    "parcel-bundler": "^1.12.3"
  },
  "devDependencies": {
    "node-sass": "^4.12.0",
    "parcel-plugin-static-files-copy": "^2.2.0",
    "pug": "^2.0.4"
  },
  "scripts": {
    "dev": "parcel index.pug",
    "build": "parcel build index.pug --out-dir dist"
  },
  "staticFiles": {
    "staticPath": "dist",
    "watcherGlob": "**"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

运行npm run dev时字体被放置在dist文件夹内,但字体本身不会加载到页面中。

我在 Chrome 中的 Networks 或类似的东西中没有错误,但也没有加载字体。

标签: csssassfontsfont-faceparceljs

解决方案


在 index.html 你需要这样的链接 fonts.css

<link rel="stylesheet" type="text/css" href="/styles/fonts.css" />

在字体.css

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

body {
  font-family: 'Storytella', serif;
}

推荐阅读