我目前正在使用Rails 5.2应用程序。我安装了npm
软件包。在此软件包中,有一个fonts
文件夹。在config/application.rb
文件中,我将资产管道配置为包含node_modules
文件夹:
config.assets.paths << Rails.root.join('node_modules')
我收到一个404 (Not Found)
错误,但是当我将fonts
文件夹移到assets
文件夹中时。
在资产预编译中,我具有以下配置:
Rails.application.config.assets.paths << Rails.root.join('node_modules')
Rails.application.config.assets.paths << Rails.root.join('node_modules/access-nyc-patterns/src/')
Rails.application.config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/
当我运行资产中所有路径名的输出时,将显示fonts
文件夹。为什么fonts
文件夹无法加载。
在application.scss
// if @font-face is used it needs to be first imported first.
@import 'elements/fonts/fonts';
为什么显示此错误?
答案 0 :(得分:0)
在设置网页样式时,通常会使用Internet上可用的主题。这些主题通常带有需要字体源的自定义字体。 @ font-face CSS规则使您可以在CSS中指定自定义字体。可以从远程服务器或用户自己的计算机上的本地安装字体中加载字体。要从远程服务器提供字体,您可以在url()函数中指定字体资源,该资源将下载并使用这些字体。如果仔细阅读给定主题提供的@ font-face规则,它将看起来像这样:
@font-face {
font-family: 'Material-Design-Iconic-Font';
src: url('../fonts/Material-Design-Iconic-Font.woff2?v=2.2.0') format('woff2'), url('../fonts/Material-Design-Iconic-Font.woff?v=2.2.0') format('woff'), url('../fonts/Material-Design-Iconic-Font.ttf?v=2.2.0') format('truetype');
font-weight: normal;
font-style: normal;
}
当客户端尝试使用错误的路径从服务器下载文件时,上述CSS规则很可能会在浏览器中引发404状态代码。 “ ../font/”仅从当前目录上移一个目录并搜索字体目录。如果您使用Rails资产管道,则将无法使用。无论您是在生产环境中还是在开发环境中运行,如果使用资产管道,Rails都会在资产目录中查找资产。现在在生产环境中,如果您运行asset:precompile,则资产将被预编译到公共目录中,并且公共目录中的任何内容都将优先于应用程序本身中的任何内容。您绝对希望将资产预编译到生产环境中,以便可以通过Web服务器快速提供资产,而不用碰到Rails机架堆栈。
在Rails ActionView中,有一个ActionView :: Helpers :: AssetUrlHelper,它提供了一些帮助程序,因此您可以轻松地链接到资产:asset_path,font_path,image_path,video_path等。现在,在CSS文件或SCSS文件中,您显然不能使用Rails辅助方法,因为它们是在ruby脚本中定义的。因此,Sprockets(资产流水线背后的强大力量)提供了您可以在CSS或SCSS脚本本身中使用的SASS功能,例如功能asset-path,如文档所示:
background: url(asset-path("image.jpg")); // background: url("/assets/image.jpg");
background: url(asset-path("image.jpg", $digest: true)); // background: url("/assets/image-27a8f1f96afd8d4c67a59eb9447f45bd.jpg");
现在,如果您不使用SASS或不想使用SASS功能,则可以直接引用资产路径:
background: url("/assets/image.jpg");
background: url("/assets/image-27a8f1f96afd8d4c67a59eb9447f45bd.jpg");
因此,对于@ font-family规则,您可以将源更改为以下内容:
src: url('/assets/Material-Design-Iconic-Font.woff2?v=2.2.0') format('woff2'), url('/assets/Material-Design-Iconic-Font.woff?v=2.2.0') format('woff'), url('/assets/Material-Design-Iconic-Font.ttf?v=2.2.0') format('truetype');
OR:
src: url('asset-path(Material-Design-Iconic-Font.woff2?v=2.2.0') format('woff2'), url('asset-path(Material-Design-Iconic-Font.woff?v=2.2.0') format('woff'), url('asset-path(Material-Design-Iconic-Font.ttf?v=2.2.0') format('truetype');