How to add css from node_modules to template.html

2019-07-20 02:19发布

问题:

I have a sapperjs app that like one you get from calling npx degit sveltejs/sapper-template my-app. I'd like to add a font. Normal people might add a line like this to app/template.html:

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

Network reasons make this impractical, so I want to host the font locally. In create-react-app I would simply import 'typeface-roboto-slab' at the top of my App.jsx or equivalent component. How can I achieve a similar effect in my sapper/svelte app?

I believe it's best to add it to app/template.html because anywhere else and the css would be scoped to an individual component. This seems like something that almost any app would need, but nothing about it in the docs that I can find.

回答1:

It's not quite as streamlined as CRA (yet!) but you can achieve this fairly simply by copying the fonts into your assets folder...

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

...then adding a <link> in your app/template.html:

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

In version 0.19, Sapper gained the ability to import CSS files directly, but it doesn't currently know how to deal with referenced files like url('./files/roboto-slab-latin-100.woff2'). That'll be supported in a future version, and then you'll be able to use fonts the same way that you can in CRA.