假设我们需要为Rails应用程序创建简单的UI组件,例如header。我们将从创建多个文件开始:
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
相同。
谢谢。
查看组件支持,捆绑资产仍然受到限制。
我设法让它与细胞Gem一起工作
gem "cells-rails"
cells 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
将css、html和js捆绑在一起的概念经常用于vuejs等javascript框架,其中三种"语言"可以包含在"单个文件组件"中。
我意识到这并不是你所要求的,但由于你已经表达了捆绑css/html/js的愿望,你可能希望考虑vuejs单文件组件。它们在整个应用程序中可重复使用,具有自己的风格和行为。