Unable to import javascript file in liquid

I’m trying to import a js file into a liquid file.

I’m using parcel bundler to combine my js files in a single js file.

scripts/scripts.js:

import 'babel-polyfill';
import './productConfigurator.js';

I include the file in theme.liquid right before like so:

{{ 'scripts.js' | asset_url | script_tag }}

Now I have a product-configurator.liquid file in the sections folder and I want to import the productConfigurator.js and call a test static function:

<div>
    <script type="module">
        import ProductConfigurator from "../scripts/productConfigurator.js"
        ProductConfigurator.callTest();
    </script>
</div>

that produces an error message:

GET https://inlivity.shop/scripts/productConfigurator.js net::ERR_ABORTED 404

when I change the scripts.js to this:

import 'babel-polyfill';
import ProductConfigurator from "./productConfigurator";

ProductConfigurator.callTest();

everything works fine.

How can I import js module files inside a liquid file?

1 Like

Hello inlivity,
Refer below link this will help you:
https://community.shopify.com/c/Shopify-Design/Include-Javascript-Files-Help/td-p/358653

I’m sorry, but that didn’t help. It just points out how to add a js file in general

1 Like

it is basically like this:

{{ ‘your-script.js’ | asset_url | script_tag }} {{ ‘your-styles.css’ | asset_url | stylesheet_tag }}

Should be copied right above tag in your theme.liquid Layout.

It may also be necessary to modify this line:

by removing defer=“defer” to ensure that jQuery loads before your javascript, which may need it.

The way you are importing javascript module is right in parcel-bundler to combine my js files in a single js file.

1 Like

Within Shopify you can’t use modules like this:

 import ProductConfigurator from "../scripts/productConfigurator.js"

You’ll want to use liquid to import it as well, like you were doing with {{ ‘scripts.js’ | asset_url | script_tag }}

However If you are coding a theme in your local machine I’d recommend that you just make one bundle with everything into one single file like app.js

Kind regards,
Diego

Had the same issue, resolved it by changing the import from this:

{{ 'custom.js' | asset_url | script_tag }}

to this:

<script defer src="{{ 'custom.js' | asset_url }}"></script>

so you can put all attributes your like on the script tag.

Overall, liquid is s**t (and so is the formatting of this blog answers that do not support proper markdown).

1 Like