Transforming JavaScript code with Liquid inline(s) in Shopify to make it less readable and harder to understand

Today, I discovered that reducing JavaScript in the js.liquid file can be quite challenging.

I'm using gulp and typescript for my project:

This is a function call from my main TypeScript file that includes inline liquid code:

ajaxLoader("{{ 'logo_black.svg' | asset_url }}")

Below is the module for ajaxLoader:


 export function ajaxLoader ( URI : string | URL ) : XMLHttpRequest {

    let ajax = new XMLHttpRequest();
        ajax.open( "GET", URI, true );
        ajax.send();
        ajax.onload = (e : any) => {
            let parser = new DOMParser();
            let doc = parser.parseFromString( ajax.responseText, "image/svg+xml" );
            document.getElementsByTagName("body")[0].appendChild(doc.getElementsByTagName("svg")[0]);
        };

    
    return ajax;

 }

One of my tasks involves the following function:

function typescript ( done ) {

    let $browserify = browserify({
            entries : paths.entry
        })
        .plugin(tsify, _typescriptConfig)
            .on("error", log)
        .bundle()
            .on("error", log)
        .pipe(source("theme.js"))
            .on("error", log)
        .pipe(buffer())
            .on("error", log)
        .pipe($.uglify())
            .on("error", log)
        .pipe($.rename((path) => {
            path.extname = ".js.liquid";
        }))
        .pipe(gulp.dest(paths.build))
    ;

    done();
}

The code runs without errors and successfully creates the minified file. However, when attempting to sync asset folders using Shopify CLI, an error occurs due to a {{ symbol in the minified file:

XX:XX:XX ERROR  » update assets/theme.js.liquid:
  Liquid syntax error (line 1): Variable '{{var t=r,i=l,n=e,s=a.slice(1);const o=i[n]||{}' was not properly terminated with regexp: /\}\}/

Is there a workaround for this issue during local development that still allows me to minify the file, or should I place all liquid calls inside inline script tags on the required page?

Alternatively, would using Hydrogen be a better option?

I found this article unhelpful

Answer №1

To segment your JavaScript code, save it in a separate .js file within the assets directory, and later retrieve it using the URL filter.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unexpected behavior: Promise.catch() fails to catch exception in AngularJS unit test

During the process of writing Jasmine unit tests for my Typescript app and running them via Resharper, I encountered an issue with executing an action when the handler throws an exception: describe("Q Service Test", () => { var q: ng.IQService; ...

Instead of leaving an Enum value as undefined, using a NONE value provides a more explicit

I've noticed this pattern in code a few times and it's got me thinking. When you check for undefined in a typescript enum, it can lead to unexpected behavior like the example below. enum DoSomething { VALUE1, VALUE2, VALUE3, } f ...

Encountering a compiler error due to lack of patience for a promise?

In the current TypeScript environment, I am able to write code like this: async function getSomething():Promise<Something> { // ... } And later in my code: const myObject = getSomething(); However, when I attempt to use myObject at a later po ...

Can the getState() method be utilized within a reducer function?

I have encountered an issue with my reducers. The login reducer is functioning properly, but when I added a logout reducer, it stopped working. export const rootReducer = combineReducers({ login: loginReducer, logout: logoutReducer }); export c ...

Executing multiple queries in a node.js transaction with Sequelize using an array

I am looking to include the updates on the clothingModel inside a transaction, with the condition that if it successfully commits, then update the reservationModel. This is the snippet of code I am attempting to refactor using sequelize.transaction tr ...

Tips for patiently anticipating the completed response within an interceptor

Using the interceptor, I want to display a loading spinner while waiting for subscriptions to complete. This approach works well in individual components by showing and hiding the spinner accordingly: ngOnInit() { this.spinnerService.show(); this. ...

Using Typescript to override an abstract method that has a void return type

abstract class Base{ abstract sayHello(): void; } class Child extends Base{ sayHello() { return 123; } } The Abstract method in this code snippet has a return type of void, but the implementation in the Child class returns a number. S ...

How can I set up BaconJS in conjunction with Webpack and CoffeeScript?

Currently in the process of transitioning old code to Webpack and encountering some issues... Utilizing a dependency loader in TypeScript import "baconjs/dist/Bacon.js" And a module in CoffeeScript @stream = new Bacon.Bus() Upon running the code, I en ...

Understanding a compound data type in TypeScript

Hey there, I'm new to TypeScript and I'm facing a challenge in defining the type for an object that might have the following structure at runtime: { "animals" : [ { name: "kittie", color: "blue" }, { name: ...

Exploring Shopify's Graphql capabilities - Retrieving metafields for all products

I am currently in the process of developing a unique storefront using nextJS and shopify APIs. One key feature I am working on is a personalized catalog filtering system that utilizes metafields. My goal is to efficiently retrieve all products' metaf ...

What is the best way to invoke a function only once in typescript?

Struggling to implement TypeScript in React Native for fetching an API on screen load? I've been facing a tough time with it, especially when trying to call the function only once without using timeouts. Here's my current approach, but it's ...

Trouble arises in AWS Code Pipeline as a roadblock is encountered with the Module

After many successful builds of my Angular project, it suddenly fails to build on AWS Code Build. I reverted back to a commit before any recent changes, but the error persists. When I run ng build --prod locally, it works fine. However, during the pipeline ...

Simultaneously accessing multiple APIs

I am currently facing an issue with calling two API requests sequentially, which is causing unnecessary delays. Can someone please advise me on how to call both APIs simultaneously in order to save time? this.data = await this.processService.workflowAPI1(& ...

Setting a value in Ionic 3 HTML template

Attempting to assign a value in an Ionic 3 template from the ts file while also adding css properties but encountered an issue. PROBLEM Error: Uncaught (in promise): Error: No value accessor for form control with name: 'image' Error: No va ...

Is it possible to access the generic type that a different generic type inherits in TypeScript?

I've developed an interface specifically designed for types capable of self-converting to IDBKey: interface IDBValidKeyConvertible<TConvertedDBValidKey extends IDBValidKey> { convertToIDBValidKey: () => TConvertedDBValidKey; } My goal n ...

Typescript: require generic types to include specific keys at all times

Is there a way to ensure that the function below only accepts a data object if it contains an id key, and then allows us to access the id from the data object? function someFuntion<T>(data : T){ const id = data['id'] //Error : Element imp ...

How can Angular JS handle multiple validators being triggered at once?

Hey there, I'm currently working with validators in my Angular form setup. Here's a snippet of how it looks - I utilize Validators.compose to combine custom validators. The errors from these validators are then displayed on the HTML component. My ...

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

Using boolean value as default input value in React

When trying to set the default value of a controlled checkbox input from my request, I encountered an error stating "Type 'boolean' is not assignable to type 'string | number | readonly string[] | undefined'". Do you have any suggestion ...

Looking for a solution to correct an Enoent error that occurred while trying to install Zurb Foundation for Apps via the command line?

After installing Node.js and updating my $PATH environment, I encountered persistent errors while attempting to install Zurb Foundation for Apps. If anyone has any suggestions on how to resolve this issue, I would greatly appreciate it. Thank you! The com ...