Rails 6 및 Webpacker가 포함된 ChartJS
목차
다루는 내용
Setting up ChartJS on a vanilla Rails 6 application
이 글을 쓰게 된 계기
For a long time now I wanted to build an uptime tracker with a clean developer friendly UX. Having used Pingdom in my workplace I found it quite inflexible and I "think" I can do better. 🤞
My professional experience was in RoR although pre Rails 6 and still using Sprockets. When building my uptime tracker I wanted to use ChartJS for visualizations and it took me a surprisingly long time to figure out how to do so. So I thought I'd share my findings.
Webpacker 및 스프로킷
Sprockets is a ruby library for compiling and serving web assets.
The latest version of Rails (I'm not sure at what point they made this switch) uses Webpacker.
Think of webpacker as an alternative to sprockets. It makes use of WebPack under the hood to help manage JS in Rails.
When using JS with Webpacker it's important to understand scope. I still haven't wrapped my head around using webpacker properly yet, but know this, Webpack does not make modules available to the global scope by default. This is part 1 of what tripped me up.
바닐라 레일즈 6 앱에서 ChartJS 설정하기
1단계: Vanilla Rails 앱
레일이 설치되어 있는지 확인하십시오. 나는 일반적으로
rbenv
를 사용하는 것을 선호합니다. 다른 루비 버전을 더 쉽게 관리할 수 있습니다.rails new chartjs-example
를 사용하여 앱을 만듭니다. rails generate controller Home index
routes.rb
를 편집합니다.Rails.application.routes.draw do
root to: 'home#index'
end
rails s
를 실행한 다음 웹 브라우저에서 localhost:3000
로 이동합니다. 빈 페이지가 표시되어야 합니다. 이제 기본 홈 페이지가 있는 Vanilla Rails 6 애플리케이션이 있습니다.
2단계: ChartJS 설치
yarn add chart.js
/app/javascript/packs/application.js
로 이동한 다음 추가import Chart from 'chart.js/auto';
할 수 있습니다.단순히
import Chart from 'chart.js/auto';
를 포함하면 작동하지 않으므로 require 'chart.js'
를 포함해야 합니다. 지침here에 따라 특정 모듈을 가져오도록 선택할 수 있습니다.이것은 오랫동안 나를 넘어 뜨린 것의 2 부입니다.
3단계: 차트 만들기
app/views/home/index.html.erb
로 이동하여 다음을 추가합니다.<canvas id="myChart" width="400px" height="400px"></canvas>
그런 다음 스크립트 태그를 만들고 새 차트 개체를 인스턴스화하여 캔버스를 업데이트할 수 있습니다.
<script>
var myChart = new Chart(ctx, {...});
</script>
당신은 할 수 없습니다. 앞에서 언급했듯이 webpacker는 기본적으로 전역 범위에 포함되지 않습니다. 위의 작업을 수행하고 페이지를 방문하면 콘솔에서 오류 메시지가 표시됩니다.
잡히지 않은 참조 오류: 차트가 정의되지 않았습니다.
대신 다음을 수행해야 합니다.
application.js
에 다음 줄을 추가합니다. 거기에 ChartJS 모듈을 가져오면 해당 범위 내에서 Chart
에 액세스할 수 있습니다.document.addEventListener('turbolinks:load', () => {
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: JSON.parse(ctx.canvas.dataset.labels),
datasets: [{
data: JSON.parse(ctx.canvas.dataset.data),
}]
},
});
})
아직 데이터 세트를 정의하지 않았음을 알 수 있습니다. 즉
labels
(x축) 및 data
(y축)입니다. html의 data-
속성을 사용하여 이를 수행해야 합니다.index.html.erb
를 업데이트하고 이전 캔버스 라인을<canvas id="myChart" width="200px" height="100px" data-labels="<%= @data_keys %>" data-data="<%= @data_values %>" ></canvas>
app/controllers/home_controller.rb
에서class HomeController < ApplicationController
def index
@data_keys = [
'January',
'February',
'March',
'April',
'May',
'June',
]
@data_values = [0, 10, 5, 2, 20, 30, 45]
end
end
여기서
data_keys
및 data_values
는 샘플 데이터로 채워집니다.이제
http://localhost:3000/
로 이동하면 새로 생성된 차트가 표시됩니다.주요 테이크 아웃
- Rails 6 uses Webpacker and Yarn by default
- Webpack does not make modules available to the global scope by default
- Define your Chart inside application.js's scope and pass your data to the js snippet using the
data-
attributes
부록
Since I sometimes really want to see the whole file in a tutorial instead of just the change you need to make.
config/routes.rb
Rails.application.routes.draw do
root to: 'home#index'
end
app/views/home/index.html.erb
<h1>Home#index</h1>
<p>Find me in app/views/home/index.html.erb</p>
<canvas id="myChart" width="200px" height="100px" data-labels="<%= @data_keys %>" data-data="<%= @data_values %>" ></canvas>
app/controllers/home_controller.rb
class HomeController < ApplicationController
def index
@data_keys = [
'January',
'February',
'March',
'April',
'May',
'June',
]
@data_values = [0, 10, 5, 2, 20, 30, 45]
end
end
app/javascript/packs/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.
import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"
import Chart from 'chart.js/auto';
Rails.start()
Turbolinks.start()
ActiveStorage.start()
document.addEventListener('turbolinks:load', () => {
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: JSON.parse(ctx.canvas.dataset.labels),
datasets: [{
data: JSON.parse(ctx.canvas.dataset.data),
}]
},
});
})
If you found this useful please let me know! :D
Reference
이 문제에 관하여(Rails 6 및 Webpacker가 포함된 ChartJS), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/wanderingsoul/rails-6-webpacker-and-chartjs-2kek텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)