Looking for help with application of custom javascript in Rails 6 framework. I am trying to implement the small example coming from chess.js module (https://github.com/jhlywa/chess.js/blob/master/README.md) in my rails 6 newly set up app (I am running the in ubuntu subsystem on windows) which should trigger a random game of chess in the console.
index.html.erb
<script>
const chess = new Chess()
while (!chess.game_over()) {
const moves = chess.moves()
const move = moves[Math.floor(Math.random()*moves.length)]
chess.move(move)
}
console.log(chess.pgn())
</script>
My understanding is that Rails 6 uses webpacker for managing scripts like that and once I install the modules through npm and yarn I should be able to use the functionality without adding the chess.js file to the /app/javascript/ folder manually.
# NPM
npm install chess.js
# Yarn
yarn add chess.js
(I can see that chess.js have been added under config/node_modules/)
When I run above snippet I get an error:
Uncaught ReferenceError: require is not defined
and when I omit the first line in the above snippet then I get:
Uncaught ReferenceError: Chess is not defined
I was trying also to place the chess.js in the /app/javascript/packs folder and then load that through
import "chess.js"
require("channels")
require("packs/chess")
in the application.js, but it is all leaping in the dark with my little experience with the Rails framework.
Would you please demonstrate correct implementation of this small example? Is it possible to implement this script in the Rails 6 framework?