如何使用 Webpack 在 Rails 6 中全局使用 JavaScript 函数? [英] How do I make a JavaScript function available globally in Rails 6 with Webpack?

查看:58
本文介绍了如何使用 Webpack 在 Rails 6 中全局使用 JavaScript 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为 Rails 6 的初学者.每当我单击 Roar Link 时,它都会给我以下错误.下面附上以下文件.我只想将自定义文件(demo.js)添加到我的代码中,以便我可以在下面的代码中测试 JavaScript 的行为.Rails 5 上的 Java Script 行为与 Rails 6 不同.

As a beginner on Rails 6. Whenever, i click on the Roar Link then it gives me the following error. The following files are attached below. I just want to add custom file(demo.js) into my code so that i can test the behavior of JavaScript in my following code. Java Script behavior on Rails 5 is different from the Rails 6.

请给我更好的解决方案,以便我解决我的问题.我尝试了有关堆栈溢出的所有答案.

Kindly give me the better solution so that i can solve my problem. I tried all of answers on stack overflow.

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

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    
  </head>

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

demo.js (app/javascript/packs/demo.js)

function jsRoar(name) {
    alert('I am ' + name + '. Hear me roar!');
  }

application.js (app/javascript/packs/application.js)

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

index.html.erb (views/demo/index.html.erb)

<h1>This is the index Page</h1>
<br/>
<%= link_to('All Subjects',subjects_path) %>

<%= link_to('Roar', '#', :onclick => "jsRoar('JavaScript'); return true;") %>

demo_controller.rb

class DemoController < ApplicationController
  
  layout 'application'
  
  def index
  render ('index')
  end

  def hello
  render ('hello')
  end

end

宝石文件

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.6'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.3', '>= 6.0.3.2'
# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.4.4'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Turbolinks makes navigating your web application faster. Read more: 
https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
end

group :test do
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  # Easy installation and use of web drivers to run system tests with browsers
  gem 'webdrivers'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

推荐答案

您正在考虑使用旧方法.我在这里解释过:

You're thinking of the old way of doing it. I've explained it here:

https://stackoverflow.com/a/56549843/1238868

这是一种更现代的方式来做您正在尝试的事情.

Here's a more modern way of doing what you're trying.

<%= link_to('Roar', '#', data: {roar: 'JavaScript'}) %>

在 demo.js 中:

In demo.js:

document.addEventListener("turbolinks:load", function() {
  document.querySelectorAll('[data-roar]').forEach(function(roaring_link) {
    roaring_link.addEventListener('click', function(event) {
      let name = roaring_link.dataset['roar']
       alert('I am ' + name + '. Hear me roar!');
       event.preventDefault();
       event.stopPropagation();
       return false;
    });
  });
});

请注意,demo.js 中的代码是自包含的,只需查看文档并将所需的功能附加到链接即可.您可以通过添加 data 属性和您希望传递给 JavaScript 函数的数据来指定这些链接是什么.

Note that the code in demo.js is self-contained and simply looks at the document and attaches the desired functionality to the links. You specify what links those are by adding a data attribute with the data that you wish to pass to your javascript function.

这可能看起来很复杂,但是当您掌握了它的窍门后,您会发现您的 javascript 非常干净且易于维护.

This might seem complicated but after you get the hang of it you'll find your javascript is really clean and easy to maintain.

这篇关于如何使用 Webpack 在 Rails 6 中全局使用 JavaScript 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆