javascript - Rails 6 Stimulus.js が実行されない

okwaves2024-01-25  8

新しい Rails 6 アプリ内に Stimulus.js をインストールしました。

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.

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


// 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)

import "controllers";

app/javascript/controllers/index.js 内には次のものがあります:

// Load all the controllers within this directory and all subdirectories. 
// Controller files must be named *_controller.js.

import { Application } from "stimulus"
import { definitionsFromContext } from "stimulus/webpack-helpers"

const application = Application.start()
const context = require.context(".", true, /.js$/)
application.load(definitionsFromContext(context))

次のような hello_controller.js があります。

// Visit The Stimulus Handbook for more details 
// https://stimulusjs.org/handbook/introduction
// 
// This example controller works with specially annotated HTML like:
//
// <div data-controller="hello">
//   <h1 data-target="hello.output"></h1>
// </div>

import { Controller } from "stimulus"

export default class extends Controller {
  connect() {
    console.log('HELLO');
  }
}

そして、次のように DOM 要素で使用できるように接続しました。

<div data-controller="hello">Hello, world</div>

webpacker がすべてをバンドルし、サイトを更新すると、console.log が開発コンソールに表示されず、エラー メッセージも表示されません。



------------------------

私のセットアップ (デフォルト) の何が問題なのか完全にはわかりませんが、このリポジトリのセットアップは機能しました。https://github.com/rodloboz/stimulus-rails

1

Thanks は別の設定です。 1 つは gem ラッパーを使用するためのもので、もう 1 つは npm を介して使用するものです

– クミトフ

2021 年 8 月 4 日 11:32

総合生活情報サイト - OKWAVES
総合生活情報サイト - OKWAVES
生活総合情報サイトokwaves(オールアバウト)。その道のプロ(専門家)が、日常生活をより豊かに快適にするノウハウから業界の最新動向、読み物コラムまで、多彩なコンテンツを発信。