在全局CSS文件中使用本地资产吗?

huangapple go评论53阅读模式
英文:

Use local assets inside of global CSS file?

问题

如果我有一个全局的CSS文件,其中定义了一些基本的颜色和字体等内容,并在我的顶级布局文件中使用简单的 `import "$lib/assets/app.css"` 导入它,那么如何在该CSS文件中引用位于`/lib/assets`文件夹中的本地字体和图像呢?目前似乎我必须将这些文件放入`/static`文件夹,但这会导致在构建时出现警告,更重要的是,它们仅在浏览器中缓存4小时。

举个例子,在我的`$lib/assets/app.css`文件中有类似以下内容:

```css
@font-face {
  font-family: "Custom";
  src: url("/fonts/Bitter-Regular.ttf");
  font-display: swap;
}

当该字体文件放在/static文件夹中时,这是正常工作的,但我更愿意将其放在$lib/assets中,因为这样做可能会使它成为不可变构建的一部分,缓存时间更长。


<details>
<summary>英文:</summary>

If I have a global CSS file which defines some basic colors and fonts and all that, and include it in my top-level layout file with a simple `import &quot;$lib/assets/app.css&quot;`, then how can I reference local fonts and images from within that css file, which are also in the `/lib/assets` folder? Currently it seems I have to put those files into `/static`, but that results in warnings when creating a build, and more importantly, they get cached in the browser for only 4 hours.

As an example, I have something like this in my `$lib/assets/app.css` file:

@font-face {
font-family: "Custom";
src: url("/fonts/Bitter-Regular.ttf");
font-display: swap;
}


That works fine when that font is placed in the `/static` folder but I&#39;d rather have it placed in `$lib/assets` because presumably that would mean it becomes part of the immutable build and gets cached way way longer.

</details>


# 答案1
**得分**: 5

你可以在你的CSS中直接使用`$lib`:

```css
@font-face {
  font-family: "Custom";
  src: url("$lib/assets/fonts/Bitter-Regular.ttf");
  font-display: swap;
}
英文:

You can just use $lib in your CSS:

@font-face {
  font-family: &quot;Custom&quot;;
  src: url(&quot;$lib/assets/fonts/Bitter-Regular.ttf&quot;);
  font-display: swap;
}

huangapple
  • 本文由 发表于 2023年3月7日 03:10:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定