#したいこと
・Railsアプリのルートディレクトリにfrontendディレクトを作り、その中にフロントエンド周りのjsファイルを置いてwebpackでapp/assets/javascripts/に吐き出す。その後application.html.erbから読み込む
#現在の状況
・app/assets/javascripts/に吐き出すことはできたが、application.html.erbから読み込まれてない。
#コード
webpack.config.js
1const path = require('path') 2 3module.exports = { 4 mode: 'development', 5 entry: { 6 app: './src/javascripts/application.js', 7 }, 8 output: { 9 path: path.resolve(__dirname, '../app/assets/javascripts'), 10 filename: 'bundle.js' 11 }, 12 module: { 13 rules: [ 14 { 15 test: /.js$/, 16 use: [ 17 { 18 loader: 'babel-loader', 19 options: { 20 presets: [ 21 // プリセットを指定することで、ES2018 を ES5 に変換 22 '@babel/preset-env', 23 // React の JSX を解釈 24 '@babel/react' 25 ] 26 } 27 } 28 ] 29 } 30 ] 31 } 32}
application.html.erb
1<!DOCTYPE html> 2<html> 3 <head> 4 <title>UnimaApp</title> 5 <%= csrf_meta_tags %> 6 <%= csp_meta_tag %> 7 8 <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> 9 <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> 10 </head> 11 12 <body> 13 <%= yield %> 14 </body> 15</html>
app/assets/javascripts/application.js
1// This is a manifest file that'll be compiled into application.js, which will include all the files 2// listed below. 3// 4// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's 5// vendor/assets/javascripts directory can be referenced here using a relative path. 6// 7// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the 8// compiled file. JavaScript code in this file should be added after the last require_* statement. 9// 10// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details 11// about supported directives. 12// 13//= require rails-ujs 14//= require activestorage 15//= require turbolinks 16//= require_tree . 17 18console.log('hello');
config/initialize/assets.rb
1# Be sure to restart your server when you modify this file. 2 3# Version of your assets, change this if you want to expire all your assets. 4Rails.application.config.assets.version = '1.0' 5 6# Add additional assets to the asset load path. 7# Rails.application.config.assets.paths << Emoji.images_path 8# Add Yarn node_modules folder to the asset load path. 9Rails.application.config.assets.paths << Rails.root.join('node_modules') 10 11# Precompile additional assets. 12# application.js, application.css, and all non-JS/CSS in the app/assets 13# folder are already added. 14Rails.application.config.assets.precompile += %w( *.js *.css )
#ディレクトリ構造
app
|---assets
| |----javascripts
| |-----application.js
| |-----bundle.js(webpackで吐き出したjsファイル)
|
|---frontent
| |-----src
| |----javascripts
| |---application.js(entry point)
#回答していただきたいこと
webpackでバンドルしたjsファイルをapp/assets/application.jsから読み込み最終的にapplication.html.erbから読み込むにはどしたらいいか。
上記の内容を踏まえてご回答お願いいたします
あなたの回答
tips
プレビュー