如何在 rails 中组织 SCSS?

How do I organize SCSS in rails?

我刚刚启动了一个新的 rails 项目,我试图从一个开源 rails 项目中参考他们如何构建他们的应用程序。

Link to the open sourced project

我注意到他们有多种布局,例如管理员,应用程序,家庭..等。每个都可以通过 stylesheet_link_tag 加载不同的样式表。

例如 focus_home.html.erb:

<!-- Load styles -->
<%= stylesheet_link_tag 'focus_home' %>
<%= stylesheet_link_tag 'app/components/modal' %>

在他们的 app/assets/stylesheets 目录中,他们有 focus_home.scss

我尝试遵循他们的架构,其中我有多个 css 文件,我调用具有不同布局的不同样式表。

我创建了我的 home.scsshome.html.slim

使用

当我启动 rails 服务器并尝试加载 home 页面时,出现以下错误

Asset filtered out and will not be served: add
`Rails.application.config.assets.precompile += %w( home.css )` to
`config/initializers/assets.rb` and restart your server

基本上它让我告诉rails预编译home.scss。但是,当我浏览开源项目的代码库时。好像没有这行代码。预编译就像变魔术一样发生。

所以我想知道我错过了什么?

==============

编辑:进一步解释案例

在他们的项目中,他们没有像普通rails项目那样有一个application.css文件。

/*  * This is a manifest file that'll be compiled into application.css, which will include all the files  * listed below.  * 
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,  * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.  *  * You're free to add application-wide styles to this file and they'll appear at the bottom of the  * compiled file so the styles you add here take precedence over styles defined in any styles  * defined in the other CSS/SCSS files in this directory. It is generally better to create a new  * file per style scope.  *  *= require_tree .  *= require_self  */

相反,在他们的 application.scss 中,它是这样的

@charset "utf-8";

@import "vars/base";
@import "constants";

// Libraries
@import 'bootstrap';

@import 'app/mixins/*';

@import 'basscss';

@import '_deprecated/basspluss';
@import '_deprecated/utility';
@import '_deprecated/nocss_vars';
@import '_deprecated/nocss';
@import '_deprecated/nocss_mq';

@import "app/main";

@import "base/*";
@import "utilities/*";
@import "app/components/*";
@import "components/*";
@import "app/slop";

@import 'libs/owl.carousel';
@import 'libs/owl.transitions';
@import 'libs/owl.theme';

@import 'c3/c3'

所以我想知道他们实际上是如何进行预编译的?

您不需要在 application.scss 和 must only use @import CSS rules 中使用 Sprockets 注释。

来自 rails-sass 文档:

Sprockets provides some directives that are placed inside of comments called require, require_tree, and require_self. DO NOT USE THEM IN YOUR SASS/SCSS FILES. They are very primitive and do not work well with Sass files. Instead, use Sass's native @import directive which sass-rails has customized to integrate with the conventions of your Rails projects.

然后,如果您有任何其他需要预编译的 .scss,您将必须使用 Rails.Application.config.assets.precompile 指令显式添加它们,然后链轮 railtie 将完成剩下的工作!

回答你原来的问题,开源项目之所以不需要指定要预编译的资源是因为他们在config/environment/production.rb文件中使用了config.assets.compile = true。这显然是一个非常糟糕的做法,我不建议您在生产环境中将此指令切换为 true ...您最终会得到一个缓慢的代码,发出大量请求并且页面加载缓慢.