Code Mirror некорректно отображается в приложении Heroku Rails 6 - PullRequest
1 голос
/ 21 января 2020

Я недавно добавил редактор зеркал кода в свое приложение rails 6. Я смог заставить все работать нормально в моей локальной среде (Ubuntu 18.04), но когда я развернул приложение на heroku, редактор зеркала кода отображает фактическую область редактирования текста намного ниже div. Похоже, что он заполняет его икс здесь это скриншот. Х рядом с верхом фактически являются частью верхнего редактора, который не показан, а нижние х являются частью основного редактора на рисунке.

Вот мое приложение. js file:

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")
import { autocompleteExport } from '../custom/autocomplete';
import { initialize } from '../custom/editor';
import { formatToc } from '../custom/page_display';

window.jQuery = $;
window.$ = $;

$(document).on("turbolinks:load", autocompleteExport.categories)
$(document).on("turbolinks:load", autocompleteExport.search)
$(document).on("turbolinks:load", autocompleteExport.admins)
$(document).on("turbolinks:load", initialize)
$(document).on("turbolinks:load", formatToc)

и вот файл редактора, который инициализирует редакторы:

import CodeMirror from 'codemirror/lib/codemirror.js'
import 'codemirror/lib/codemirror.css'
import 'codemirror/mode/markdown/markdown.js'

function initialize(){
    let textArea = document.getElementById('page_edit_content')
    let editor = document.getElementById('content-editor')

    if(textArea && !editor){
        var contentEditor = CodeMirror.fromTextArea(textArea, {
                                                    lineWrapping: true,
                                                    mode: "markdown",
                                                });

        contentEditor.display.wrapper.id = "content-editor"
    }

    textArea = null
    editor = null

    textArea = document.getElementById('page_edit_summary')
    editor = document.getElementById("summary-editor")

    if(textArea && !editor){
        var contentEditor = CodeMirror.fromTextArea(textArea, {
            lineWrapping: true,
            mode: "markdown",
        });

        contentEditor.display.wrapper.id = "summary-editor"
    }

    textArea = null
    editor = null

    textArea = document.getElementById('page_content')
    editor = document.getElementById("new-content-editor")

    if(textArea && !editor){
        var contentEditor = CodeMirror.fromTextArea(textArea, {
            lineWrapping: true,
            mode: "markdown",
        });

        contentEditor.display.wrapper.id = "new-content-editor"
    }

    textArea = null
    editor = null

    textArea = document.getElementById('page_summary')
    editor = document.getElementById("new-summary-editor")

    if(textArea && !editor){
        var contentEditor = CodeMirror.fromTextArea(textArea, {
            lineWrapping: true,
            mode: "markdown",
        });

        contentEditor.display.wrapper.id = "new-summary-editor"
    }
}

export {initialize}

Наконец, вот одно из представлений, которое имеет проблему:

<% @page_title = "New Page" %>

<div class="container form-container">
  <%= form_for @page, url: world_pages_path(params[:world_name]), html: {style: "width: 100%"} do |f| %>
    <%= render 'shared/error_messages', errors: flash[:errors] %> 
    <div class="form-group">
      <%= f.label :title %>
      <%= f.text_field :title, autofocus: true, class: "form-control" %>
    </div>
    <div class="form-group">
      <%= f.label :summary %>
      <%= f.text_area :summary, class: "form-control" %>
    </div>
    <div class="form-group">
      <%= f.label :content %>
      <%= f.text_area :content, class: "form-control" %>
    </div>
    <div class="form-group">
      <%= f.submit "Create!", class: "btn btn-primary" %>
    </div>
    <% if params[:category] %>     
    <%= hidden_field_tag :category, params[:category] %>
    <% end %>
  <% end %>
</div>

Я довольно Я бы очень признателен за то, что может быть причиной любой помощи.

edit:

Посмотрев немного через мои браузеры devtools, похоже, что проблема может исходить из css неправильно загружается в мой файл editor.js, куда я импортирую файлы css для кода зеркала.

edit-2:

Когда я удаляю css оператор import из файла editor.js, я получаю такое же поведение при разработке, поэтому я точно знаю, что это проблема. Если кто-нибудь знает правильный способ импорта стилей из узловых модулей, это было бы очень полезно

1 Ответ

1 голос
/ 21 января 2020

Если кто-нибудь столкнется с чем-то подобным в будущем, я смог найти ответ.

Проблема была связана с моим неправильным пониманием веб-пакета.

Я непосредственно импортировал css из модуля узла в файл editor.js. Я до сих пор не эксперт по веб-пакетам, поэтому я не могу сказать, почему это работает локально, но он неправильно настроил файлы css, которые должны быть скомпилированы веб-пакетом в производство.

Вместо этого было исправлено создайте файл application.scss в app/javascript/src. Именно в этом файле я добавил @import 'codemirror/lib/codemirror.css';

После этого я добавил import '../src/application.scss' в свой файл application.js, чтобы веб-пакет знал, как скомпилировать css.

Наконец, Я добавил <%= stylesheet_pack_tag 'application', 'data-turbolinks-track': 'reload' %> в свой файл макета application.html.erb, который извлекает css из скомпилированных файлов.

...