DRY(Don't Repeat Yourself) is a basic principle in programming. This article provides a very trivial but useful way for rails developers to reuse their javascript code in multiple files.
The usual folder structure in a rails 6 app looks like
-app/
|-assets/
|-channels/
|-controllers/
|-helpers/
|-javascript/
|-packs/
|-application.js
|-...(and other folders)
If you have multiple javascript files in the app/javascript/ folder and you want to reuse the code between these files
-app/
|-javascript/
|-packs/
|-application.js
|-first.js
|-second.js
Consider
// app/javascript/packs/first.js
const calculateArea = (params_here) => {
// calculate and return area
}
const calculateVolume = (params_here) => {
// calculate and return volume
}
now if you want to use the function calculateArea and calculateVolume in your second.js you can export these functions from first.js and then import them in second.js.
// app/javascript/packs/first.js
const calculateArea = (params_here) => {
// calculate and return area
}
const calculateVolume = (params_here) => {
// calculate and return volume
}
export { calculateArea, calculateVolume };
and import them for re-use
// app/javascript/packs/second.js
import { calculateArea, calculateVolume } from './first';
// now you can use the imported consts/variables/functions in this file
Bonus
To include your custom javascript code into application.js pack, considering you've app/javascript/packs/first.js and app/javascript/packs/second.js, do this
// app/javascript/packs/application.js
import 'packs/first'
import 'packs/second'
Cover Image credits Clem Onojeghuo on Unsplash
Top comments (1)
yes, definitely. That example was only to demonstrate the import method/syntax.