如何在 Rails 6 中要求自定义 JS 文件 [英] How to require custom JS files in Rails 6

查看:40
本文介绍了如何在 Rails 6 中要求自定义 JS 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试 Rails 6.0.0.rc1,它似乎已将默认的 javascript 文件夹从 app/assets/javascript 移动到 app/javascript.application.js 文件现在位于 app/javascript/packs 中.现在,我想添加几个 js 文件,但由于某种原因它们没有被导入,而且我找不到任何关于如何在 Rails 6 中完成此操作的文档.我尝试了一些方法:

I'm currently trying Rails 6.0.0.rc1 which seems to have moved the default javascript folder from app/assets/javascript to app/javascript. The application.js file is now located in app/javascript/packs. Now, I want to add a couple of js files, but for some reason they don't get imported and I can't find any documentation on how this can be done in Rails 6. I tried a couple of things:

  1. app/javascript/packs下创建一个新文件夹custom_js,将我所有的js文件放在那里,然后添加一个require "custom_js"application.js.

  1. Create a new folder custom_js under app/javascript/packs, putting all my js files there and then add a require "custom_js" to application.js.

复制我在 app/javascript/channels 下的所有 js 文件(默认情况下应该包含它,因为 application.jsrequire("频道")).

Copy all my js files under app/javascript/channels (which should be included by default, since application.js has require("channels")).

require_tree . 添加到 application.js,这是以前的方法.

Adding require_tree . to application.js, which was the previous approach.

如何在 Rails 6 应用程序中加载我自己的 js 文件?

How can I load my own js files inside a Rails 6 application?

推荐答案

使用这种方法获得组织更好的代码并避免 application.html.erb 文件中的多个 javascript_pack_tags:

Get better-organized code and avoid multiple javascript_pack_tags in your application.html.erb file with this approach:

  1. 将您的自定义 example.js javascript 文件添加到 app/javascript/packs.
  2. require("packs/example") 添加到您的 application.js 文件中.
  1. Add your custom example.js javascript file to app/javascript/packs.
  2. Add require("packs/example") to your application.js file.

<小时>

我想对 Asim Hashmi 的正确答案添加评论.但是我没有足够的声誉,所以我将添加我的建议作为答案.

没有必要在 require 中包含.js"扩展名.

It isn't necessary to include the ".js" extension inside of the require.

这篇关于如何在 Rails 6 中要求自定义 JS 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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