Pass Liquid Variables to separate JavaScript file?

23 0 7

I have been playing with Variable Scope to make reusable components.

For example: 

{%- include 'modal', id: 'modal', onClick: 'modalBtn' -%}

We can pass key: value pairs to the snippet where a variable can be reassigned within the variable scope.

I was wondering if there were some way to do this by sending variables to a separate js file.

For example:

<!-- Liquid File -->
{{ 'modal.js' | asset_url | script_tag, id: "modal", onClick: "modalBtn" }}

<!-- JavaScript File -->
var modal = document.getElementById(id);
var btn = document.getElementById(onClick);

 Why would I want to do this?

I am running all js through webpack and it would be neat to send all js through compilation. Probably not possible but thought it would be cool to get some ideas here.

Shopify Expert
710 48 176

You can't pass custom liquid variables to asset files. What you can do is set some js variables in inline <script> tags and create some variables or a json object where your values are set by your liquid variables or just static text.

var modalConfig = {
  "id": "modal",
  "onClick": "modalBtn"