0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

rails6 javascriptファイルの追加方法

Posted at

app/assets/javascript/packs配下にjsファイルを作成する。

app/assets/javascript/packs/application.jsにjsファイルをコンパイルするように追記する。(test.jsという名前のファイルの場合下記のように書く)

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)


// ここに追記
require ('packs/test')

読み込まれたか確認するためにjsファイルにコンソールに表示する内容を記述。

test.js
console.log("Hello world"); // この行が読み込まれた時点で実行される

ブラウザのコンソールを確認し、表示されたらjsファイルが正常に読み込まれている!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?