Splitting a Large JavaScript File into Modular Components for a Shopify Widget

Hi Shopify Devs,

I recently ran into a challenge while working on a custom widget for a Shopify store. The widget was implemented in a single, monolithic JavaScript file, which included everything from data fetching and UI building to dynamic cart updates.

The main issue arose when I attempted to inject the JavaScript file into the app_embed_block.liquid file using the following schema configuration:

liquid:

{% schema %}
{
  "name": "Testing App",
  "target": "body",
  "stylesheet": "widget.css",
  "javascript": "main-widget.js",
  "settings": []
}
{% endschema %}

The main JavaScript file exceeded Shopify’s 10 KB file size limit, making it impossible to deploy the app or extension. To resolve this, I split the file into three modular components.

Goals for the Split

  1. Compliance with File Size Limits: By breaking the code into smaller modules, each JavaScript file stays within Shopify’s 10 KB limit for app embed blocks.
  2. Improved Maintainability: Smaller files are easier to manage, debug, and extend.
  3. Scalability: Modularity allows for easier integration of new features without impacting existing code.
  4. Reusability: Logical separation enables reuse of components across projects.

File Structure

Here’s how I structured the code:

  1. Main.js: Orchestrates the entire functionality by importing and linking Build.js and Update.js.
  2. Build.js: Handles all UI element creation and initialization logic for the widget.
  3. Update.js: Observes cart changes and dynamically updates the widget as needed.

Challenges and Community Feedback

While this modular approach solves the file size issue and improves code organisation, I’d love to hear your thoughts:

  1. Best Practices: Are there alternative ways to handle file size limitations for app embed blocks?
  2. Performance: Tips for ensuring optimal performance when observing and reacting to cart changes?
  3. Error Handling: How to handle errors across multiple interdependent modules effectively?

Conclusion

Splitting the main file into smaller, modular components not only resolved the file size limitation but also made the code more maintainable and scalable. I’m looking forward to learning from the collective expertise of this community as I refine the solution further.

Let me know your thoughts and suggestions!

Cheers,
Premnath.M