Adding highlightjs for code highlighting in Rails 7
May 08, 2023
kapilnakhwa
My code highlighting sucked in this blog, Not saying it is wonderful now, But documenting what I did here. .
In rails 7 , There are multiple ways you can work with javascript,
In rails 7 , There are multiple ways you can work with javascript,
- Work with importmap, The default in Rails 7 and the future of how we use javascript ! .
- Work with NPM packages using javascript bundlers like esbuild, webpack or rollup.
I decided on using the first option, importmaps.
In rails 7 , It is likely that you already have it enabled , If not
./bin/bundle add importmap-rails
./bin/rails importmap:install
The above steps is not needed most of the time if you are using rails 7 , As Rails 7 as of today ships with importmap.
Adding in highlightjs
Adding in highlightjs
bin/importmap pin hightlight.js
This should write up highlightjs in importmaps.
❯ cat config/importmap.rb # Pin npm packages by running ./bin/importmap pin "application", preload: true pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true pin_all_from "app/javascript/controllers", under: "controllers" pin "trix" pin "@rails/actiontext", to: "actiontext.js" pin "highlight.js", to: "https://ga.jspm.io/npm:highlight.js@11.8.0/es/index.js"
This would give me capability to reference highlight.js library in my rails application.js files.
I am also using trix for WYSWUG editor for this blog. Hence, the code elements are wrapper in pre block.
Simple as that, Now in application.js .
❯ cat app/javascript/application.js // Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails import "@hotwired/turbo-rails" import "controllers" import "trix" import "@rails/actiontext" import {HighlightJS } from "highlight.js" document.addEventListener('turbo:load', (event) => { document.querySelectorAll('pre').forEach( element => { HighlightJS.highlightElement(element); }); })
This should be it. The code highlighting should be working.
