【问题标题】:how to create modular UI units (components) in Rails app?如何在 Rails 应用程序中创建模块化 UI 单元(组件)?
【发布时间】:2019-10-24 12:05:14
【问题描述】:

假设我们需要为 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-rails asset-pipeline


    【解决方案1】:

    View Component 支持,并且开箱即用的捆绑资产仍然受到限制。

    我设法让它与 cells Gem

    一起工作
    gem "cells-rails"
    

    cell 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

    【讨论】:

    • 我希望这对你有帮助,我希望能够用纯 Actionview::Component 答案更新这个答案
    • 谢谢。很快就会尝试Actionview::Component
    【解决方案2】:

    将 css、html 和 js 捆绑在一起的概念经常用于 javascript 框架,例如 vuejs,其中三种“语言”可以包含在“单个文件组件”中。

    我知道这并不是您要问的,但是由于您已经表达了捆绑 css/html/js 的愿望,您可能希望考虑使用 vuejs 单文件组件。它们在整个应用程序中非常可重用,具有自己的风格和行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-06
      • 2011-09-06
      • 2014-02-15
      • 2012-03-11
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      相关资源
      最近更新 更多