rails7でjavascriptを使用したい
Q&A
Closed
解決したいこと
rails7でjavascriptを使用したいのですが、うまく読み込めません。
記述で間違っている点、足りない点などご教授いただければ幸いです。
発生している問題・エラー
Uncaught TypeError: Failed to resolve module specifier "@hotwired/turbo-rails". Relative references must start with either "/", "./", or "../".
Javascriptを読み込みたいページで「検証」をすると出てくるメッセージです。
該当するソースコード
application.js
// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
import "./card"
import "./memo"
import "./channels"
comment_channel.js (4行目の「読み込み完了」がコンソールに表示されません)
import consumer from "channels/consumer"
if(location.pathname.match(/\/coaches\/\d/)){
console.log("読み込み完了")
consumer.subscriptions.create({
channel: "CommentChannel",
coach_id: location.pathname.match(/\d+/)[0]
}, {
connected() {
// Called when the subscription is ready for use on the server
},
disconnected() {
// Called when the subscription has been terminated by the server
},
received(data) {
const html = `
<div class="comment">
<p class="user-info">${data.user.nickname}: </p>
<p>${data.comment.text}</p>
</div>`
const comments = document.getElementById("comments")
comments.insertAdjacentHTML('beforeend', html)
const commentForm = document.getElementById("comment-form")
commentForm.reset();
}
})
}
importmap.rb
# Pin npm packages by running ./bin/importmap
pin "application"
pin "@rails/actioncable", to: "actioncable.esm.js"
pin_all_from "app/javascript/channels", under: "channels"
pin_all_from 'app/javascript', under: 'javascript'
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>MatchingGame</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.css">
<script type="text/javascript" src="https://js.pay.jp/v2/pay.js"></script>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Yomogi&display=swap" rel="stylesheet">
</head>
<body>
<%= yield %>
</body>
</html>
自分で試したこと
application.jsにimportを記述
application.html.erbにjavascript_importmap_tagsを記述
0