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

Plot the components of an array and calculate the instances that JavaScript executes

I have an array containing information about PDF files stored in a buffer. Let's imagine this array holds ten PDF files structured like this: [{ correlative: "G-22-1-06", content: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 d3 eb e9 e1 0a ...

Running Swagger within an Angular 5 environment - a step-by-step guide!

How do I integrate Swagger into my UI? Here's what I tried: import * as SwaggerUI from 'swagger-ui'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.c ...

The EventEmitter in Angular 8 is prohibiting the emission of an Object

Is there a way I can emit an Object instead of primitive data types? I have an object const amount = { currenty: 'USD', total: '10.25' }; that I need to emit to the parent component. export class MyChildComponent implements OnInit { ...

Describing a property of an interface as the determined form of a conditional type that is generic

I am currently working on defining an interface that includes a method with a conditional function definition. For example: interface Example<T> { func: T extends string ? () => string : () => number; } class ExampleClass<T extends str ...

Importing node_modules in Angular2 using TypeScript

My Angular2 app started off as a simple 'hello world' project. However, I made the questionable decision to use different directory structures for my development environment and the final deployment folder on my spring backend. This difference c ...

Issue "Value of type '{}' cannot be assigned to parameter of type 'T | (() => T)'" encountered within a React component containing a type parameter

Currently, I am attempting to achieve the following: function SomeComponent<T>({ children }: PropsType) { const [configuration, setConfiguration] = useState<T>({}) } However, I am encountering this issue: The argument of type '{}&apos ...

Labeling src library files with namespaces

I have developed a ReactJS website that interacts with a library called analyzejs which was created in another programming language. While I am able to call functions from this library, I do not have much flexibility to modify its contents. Up until now, ...

Loading dynamic components asynchronously in Vue 3 allows for improved performance and enhanced user experience

My goal is to dynamically display components based on their type. Here's how I'm approaching it: I have several similar components that should show different content depending on their type. Using the defineAsyncComponent method, I can easily im ...

Can Vue instances support private computed properties?

Vue is a versatile tool that I utilize for both service classes and components. When it comes to reactive computeds, they prove to be incredibly beneficial. However, I often find myself wanting a clear way to differentiate between public interface compute ...

When using expressjs and typescript, you may encounter an error stating that the type 'typeof <express.Router>' cannot be assigned to the parameter type 'RequestHandlerParams'

Working on my project using expressjs with the latest typescript definition file and typescript 2.3.4 from https://github.com/DefinitelyTyped/DefinitelyTyped. I've set up a router and want to access it from a subpath as per the official 4.x documentat ...

Assigning namespaces to a property of classes in typescript: A step-by-step guide

As I work on adding a declaration file to a TypeScript package, I encounter some syntax that looks like this: const Sequelize = require('Sequelize'); //... class Application { Sequelize = Sequelize; } To address this, I created a file named ...

Retrieve a specific number from an equation

With my limited knowledge of TypeScript, I am attempting to extract a specific number from an expression. The goal is to locate and retrieve the digit from the following expression. ID:jv.link.weight:234231 In the given string, I aim to extract the numb ...

Tips on revealing TypeScript modules in a NodeJS environment

Currently, I am working on developing a TypeScript library. My goal is to make this library compatible with both TypeScript and JavaScript Node projects. What would be the most effective approach for achieving this? Should I create two separate versions ...

Unraveling the mysteries of Typescript with async await

I'm facing a peculiar issue in my code that I'm struggling to identify. try { const result = await somePromise.catch((err) => { console.log(new Date()); // displays time, t0 console.log('Stats', eventLoopStats.se ...

Checkbox offering a tri-state option

Seeking help on creating a checkbox with three states. I have implemented a method to toggle between these states upon clicking. However, the issue is that this method is only triggered after the HTML changes. As a result, the checkbox's navigation be ...

Learn the process of transferring a complete JSON object into another object using Angular

I'm having trouble inserting one object into another. My JSON object is multidimensional, like this: { "item1":{ "key":"Value", "key":"Value" }, "item2":{ "key ...

What is the method for incorporating sorting into a mat-list?

I've searched for various solutions, but none seem to work with mat-list. It's crucial for me because mat-list is the only solution where drag&drop functionality works (I always face this issue with mat-table in tables and I can't find a ...

Application built with Electron and Typescript encounters module-related crash

While working on developing a client using Electron with Typescript, I encountered the following error: The configuration in tsconfig.json looks like this: { "compilerOptions": { "target": "es5", "lib": [ ...

"iOS users have reported that notifications from Firebase have mysteriously ceased to

Yesterday evening, I was experimenting with Push Notifications from Firebase on my iOS application and everything was functioning correctly. I successfully sent a notification from a Cloud Function to a specific FCM token. However, this morning, notificat ...

Using ngFor in Angular to display the API response

I am having trouble displaying a JSON response in my web panel. When attempting to show the full response, everything works perfectly. However, when I try to use ngFor, I encounter the following errors in the browser: ERROR TypeError: Cannot read property ...