Multiple Frontend JS React Sources: Best Practices
-
Currently working on a custom theme for a client and building out the JavaScript functionality with React using node and @wordpress/element an @wordpress/scripts.
There are several sections, shortcodes, and areas of the site and so I built each section as it’s own mini-app. The index.assets.php only enqueues when the shortcode is called or get_template_part loads, which works great.
However, the only problem I’m having now is sharing code between modules. In this example, a lightbox. I moved my lightbox code from my gallery source and was going to make it shared between multiple other sources.
In the link attached, I shared the partial javascript code and package from my setup. Currently I’m setting up htld-lightbox as a dependency pointing to the build files and importing htld-lightbox inside ./js/hcwhy/App.js. The issue is that I’m getting
App.js:11 Uncaught TypeError: Object(…) is not a function
for the useLightbox hook. Now the whole setup works if the htld-lightbox dep is pointed to the src folder instead of the build – BUT then the Chrome export won’t work (the chrome will be the reusable UI around the lightbox contents). This is because it’s not getting the proper babel JSX transforms – which is solved by building it. BUT then the build is not exporting the modules useLightbox and Chrome.
I feel this is the right way to organize the javascript, but I’m probably missing a webpack config to get useLightbox and Chrome exported correctly to be made available as a dependency. Another solution would be be making a global object that I can use instead of an export and build that into the dependency array of items using the lightbox.
Am I insane or is there a simpler solution out there (other than making one fat bundle).
The page I need help with: [log in to see the link]
- The topic ‘Multiple Frontend JS React Sources: Best Practices’ is closed to new replies.