В Rails 6 и приложении React отображаются только данные JSON, а не компонент React с webpack-dev-server - PullRequest
0 голосов
/ 10 апреля 2020

Я создаю приложение Rails 6 с использованием установленного веб-упаковщика и использую React в качестве моей JS инфраструктуры для внешнего интерфейса. Я следовал инструкциям по установке React, но когда я go зашел на мою страницу root, он отображает только данные json, а не компонент hello_react. Я уже работал над этим и сравнивал рельсовые приложения, но не вижу никаких выбросов.

Вот мой package.json файл:

{
  "name": "tml_dashboard",
  "private": true,
  "dependencies": {
    "@babel/core": "^7.0.0-0",
    "@babel/preset-react": "^7.9.4",
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.2.2",
    "add": "^2.0.6",
    "babel-plugin-transform-react-remove-prop-types": "^0.4.24",
    "dotenv": "^8.2.0",
    "moment": "^2.24.0",
    "moment-timezone": "^0.5.27",
    "prop-types": "^15.7.2",
    "qs": "^6.9.1",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.0-beta.16",
    "react-datepicker": "^2.13.0",
    "react-datetime-picker": "^2.9.0",
    "react-dom": "^16.13.1",
    "react-input-range": "^1.3.0",
    "react-moment": "^0.9.7",
    "react-semantic-ui-datepickers": "^2.3.0",
    "react-simple-timefield": "^3.0.0",
    "react-time-picker": "^3.9.0",
    "react_ujs": "^2.6.1",
    "semantic-ui-calendar-react": "^0.15.3",
    "semantic-ui-css": "^2.4.1",
    "semantic-ui-react": "^0.88.2",
    "turbolinks": "^5.2.0",
    "uuid": "^3.3.3",
    "webpack": "^4.41.6",
    "webpacker": "^4.6.0",
    "yarn": "^1.22.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "case-sensitive-paths-webpack-plugin": "^2.2.0",
    "webpack-dev-server": "^3.10.3"
  }
}

Мои рельсы application.html.erb на layouts странице:

<!DOCTYPE html>
<html>
  <head>
    <title>TmlDashboard</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <!-- only uses webpacker, not asset pipline  -->
    <%= stylesheet_pack_tag 'application', media: 'all' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>


  </head>

  <body>

    <%= yield %>
  </body>
</html>

мой application.js файл


// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")


import "css/site";
import "semantic-ui-css/semantic.min.css";





// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)


моя hello_react.jsx страница:


// Run this example by adding <%= javascript_pack_tag 'hello_react' %> to the head of your layout file,
// like app/views/layouts/application.html.erb. All it does is render <div>Hello React</div> at the bottom
// of the page.

import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'

const Hello = props => (
  <div>Hello {props.name}!</div>
)

Hello.defaultProps = {
  name: 'David'
}

Hello.propTypes = {
  name: PropTypes.string
}

document.addEventListener('DOMContentLoaded', () => {
  ReactDOM.render(
    <Hello name="React" />,
    document.body.appendChild(document.createElement('div')),
  )
})

моя webpacker.yml

# Note: You must restart bin/webpack-dev-server for changes to take effect

default: &default
  source_path: app/javascript
  source_entry_path: packs
  public_root_path: public
  public_output_path: packs
  cache_path: tmp/cache/webpacker
  check_yarn_integrity: false
  webpack_compile_output: true

  # Additional paths webpack should lookup modules
  # ['app/assets', 'engine/foo/app/assets']
  resolved_paths: []

  # Reload manifest.json on all requests so we reload latest compiled packs
  cache_manifest: false

  # Extract and emit a css file
  extract_css: false

  static_assets_extensions:
    - .jpg
    - .jpeg
    - .png
    - .gif
    - .tiff
    - .ico
    - .svg
    - .eot
    - .otf
    - .ttf
    - .woff
    - .woff2

  extensions:
    - .jsx
    - .mjs
    - .js
    - .sass
    - .scss
    - .css
    - .module.sass
    - .module.scss
    - .module.css
    - .png
    - .svg
    - .gif
    - .jpeg
    - .jpg

development:
  <<: *default
  compile: true

  # Verifies that correct packages and versions are installed by inspecting package.json, yarn.lock, and node_modules
  check_yarn_integrity: false

  # Reference: https://webpack.js.org/configuration/dev-server/
  dev_server:
    https: false
    host: localhost
    port: 3035
    public: localhost:3035
    hmr: false
    # Inline should be set to true if using HMR
    inline: true
    overlay: true
    compress: true
    disable_host_check: true
    use_local_ip: false
    quiet: false
    pretty: false
    headers:
      'Access-Control-Allow-Origin': '*'
    watch_options:
      ignored: '**/node_modules/**'


test:
  <<: *default
  compile: true

  # Compile test packs to a separate directory
  public_output_path: packs-test

production:
  <<: *default

  # Production depends on precompilation of packs prior to booting for performance.
  compile: false

  # Extract and emit a css file
  extract_css: true

  # Cache manifest.json for performance
  cache_manifest: true

моя environments/development.rb страница:

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded on
  # every request. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = true

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports.
  config.consider_all_requests_local = true

  # Enable/disable caching. By default caching is disabled.
  # Run rails dev:cache to toggle caching.
  if Rails.root.join('tmp', 'caching-dev.txt').exist?
    config.action_controller.perform_caching = true
    config.action_controller.enable_fragment_cache_logging = true

    config.cache_store = :memory_store
    config.public_file_server.headers = {
      'Cache-Control' => "public, max-age=#{2.days.to_i}"
    }
  else
    config.action_controller.perform_caching = false

    config.cache_store = :null_store
  end

  # Store uploaded files on the local file system (see config/storage.yml for options).
  config.active_storage.service = :local

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = false

  config.action_mailer.perform_caching = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Highlight code that triggered database queries in logs.
  config.active_record.verbose_query_logs = true

  # Debug mode disables concatenation and preprocessing of assets.
  # This option may cause significant delays in view rendering with a large
  # number of complex assets.
  config.assets.debug = true

  # Suppress logger output for asset requests.
  config.assets.quiet = true

  # Raises error for missing translations.
  # config.action_view.raise_on_missing_translations = true

  # Use an evented file watcher to asynchronously detect changes in source code,
  # routes, locales, etc. This feature depends on the listen gem.
  config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end

страница контроллера дома:

class OutagesController < ApplicationController
  before_action :find_outage, only: [:show, :update, :destroy]

  def index
    @outages = Outage.all 
    render :json => @outages, status: :ok 
  end

  def show
    render :json => @outage, status: :ok 
  end

  def create
    @outage = Outage.create(outage_params)
    if @outage.save 
      render :json => @outage, status: :ok 
    else   
      render :json => { errors: @outage.errors.full_messages }, status: @unprocessible_entity
    end 
  end

  def update
    if @outage.update(outage_params) 
      render :json => @outage, status: :ok 
    else      
      render :json => { errors: @outage.errors.full_messages }, status: @unprocessible_entity
    end
  end

  def destroy
    @outage.delete 
    render :json => "Outage deleted successfully!"
  end

  private 

  def find_outage 
    @outage = Outage.find(params[:id])
  end

  def outage_params 
    params.require(:outage).permit(:end_time, :is_recurring, :frequrency, :service_id, :reason)
  end
end

и, наконец, моя страница маршрутов:

Rails.application.routes.draw do

  root 'outages#index'


  resources :services, only: [:index, :show]  
  resources :user, only: :show 
  resources :outages 

# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

...