首页 > 解决方案 > 如何在 Rails 应用程序中创建模块化 UI 单元(组件)?

问题描述

假设我们需要为 Rails 应用程序创建简单的 UI 组件,例如标题。我们将从创建多个文件开始:

1)app/views/partials/_header.erb

2)app/assets/stylesheets/_header.scss

3)app/assets/javascript/_header.js

之后,我们需要将它们包含在适当的视图或清单文件中。

问题:

有没有一种简单的方法可以将这些文件移动到单个文件夹中?例如:

app
|-- ui_components
|   |-- header
|   |   |-- view.erb
|   |   |-- style.scss
|   |   |-- script.js

并且,如果是.scss,请通过以下方式将它们包括在内app/assets/stylesheets/application.scss

@import "ui_components/header/style"
@import "ui_components/footer/style"
...

.js.

谢谢。

标签: ruby-on-railsasset-pipeline

解决方案


查看组件支持,并且捆绑资产仍然受到限制。

我设法让它与细胞宝石一起工作

gem "cells-rails"

单元格 gem 允许您将视图组件放入app/cells,请参阅http://trailblazer.to/gems/cells/

application.rb你需要

def self.cells_with_assets
  all_cell_file_names = Dir.glob("app/cells/**/*.rb")
  all_cell_file_names.map do |f|
    f.match(/app\/cells\/([a-z_\/]*)\.rb/)[1].classify
  end
end    

config.cells.with_assets = Application.cells_with_assets

要使其与 SCSS 一起使用,您还需要确保包含其中的文件,因此在您的操作中application.scss

/* Include all SCSS Files in the cells directory
*= require_tree ../../cells
*/

当然,我建议ActionView::Component现在使用,因为它现在是 rails 核心的一部分,从 5.x 开始(不确定)。

https://github.com/github/actionview-component


推荐阅读