如何在 Rails 6 中要求自定义 JS 文件 [英] How to require custom JS files in Rails 6
问题描述
我目前正在尝试 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:
在
app/javascript/packs
下创建一个新文件夹custom_js
,将我所有的js文件放在那里,然后添加一个require "custom_js"
到application.js
.
Create a new folder
custom_js
underapp/javascript/packs
, putting all my js files there and then add arequire "custom_js"
toapplication.js
.
复制我在 app/javascript/channels
下的所有 js 文件(默认情况下应该包含它,因为 application.js
有 require("频道")
).
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:
- 将您的自定义
example.js
javascript 文件添加到app/javascript/packs
. - 将
require("packs/example")
添加到您的application.js
文件中.
- Add your custom
example.js
javascript file toapp/javascript/packs
. - Add
require("packs/example")
to yourapplication.js
file.
<小时>
我想对 Asim Hashmi 的正确答案添加评论.但是我没有足够的声誉,所以我将添加我的建议作为答案.
没有必要在 require 中包含.js"扩展名.
It isn't necessary to include the ".js" extension inside of the require.
这篇关于如何在 Rails 6 中要求自定义 JS 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!