首页 > 解决方案 > 如何在 Svelte 中将 CSS 从 node_modules 添加到 template.html

问题描述

我有一个 sapperjs 应用程序,就像你从 call 获得的应用程序一样npx degit sveltejs/sapper-template my-app。我想添加一个字体。普通人可能会在下面添加这样的一行app/template.html

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto+Slab">

网络原因使这不切实际,所以我想在本地托管字体。在 create-react-app 中,我会简单地import 'typeface-roboto-slab'放在我的 App.jsx 或等效组件的顶部。如何在我的 sapper/svelte 应用程序中实现类似的效果?

我相信最好将它添加到app/template.html其他任何地方,并且 css 将被限定为单个组件。这似乎是几乎任何应用程序都需要的东西,但在我能找到的文档中却没有。

标签: cssimportnode-modulessvelte

解决方案


它不像 CRA 那样精简(还没有!),但您可以通过将字体复制到assets文件夹中来相当简单地实现这一点......

npm i typeface-roboto-slab
cp -r node_modules/typeface-roboto-slab assets

...然后<link>在您的app/template.html:

<link rel="stylesheet" href="typeface-roboto-slab/index.css">

在 0.19 版本中,Sapper 获得了直接导入 CSS 文件的能力,但它目前不知道如何处理引用的文件,如url('./files/roboto-slab-latin-100.woff2'). 这将在未来的版本中得到支持,然后您就可以像在 CRA 中一样使用字体。


推荐阅读