简体   繁体   中英

Rails 6 Stimulus.js won't run

I have Stimulus.js installed inside of my new Rails 6 app.

Inside of my packs/application.js file, I have the following:

// 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";

Inside of app/javascript/controllers/index.js , I have the following:

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

I have a hello_controller.js that looks like

// 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');
  }
}

And I have plugged it up to use on a DOM element like so:

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

When webpacker bundles everything and I refresh the site, my console.log does not render in my dev console nor do I see any error messages.

Not entirely sure whats wrong with my setup (its the default), but, this repo setup worked! https://github.com/rodloboz/stimulus-rails

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM