How to Uglify Javascript with Liquid inline(s) - Shopify

599 views Asked by At

So today I learnt that minimising JavaScript inside of js.liquid file is a nightmare.

I'm building with gulp & typescript:

This is a call from my entry TypeScript file that uses a liquid inline:

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

This is 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 is as follows:

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();
}

This runs with no errors and builds the file, nice and ugly. However when it comes to the Shopify CLI to sync asset folders, it finds a {{ in the now minimised file and gives this error:

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 (local development side) way to work around this that will still allow me to uglify the file, or will I have to do all liquid calls inside inline script tags on the required page?

Or Am I better just using Hydrogen

This article has no help whatsoever

1

There are 1 answers

4
Kudo On

You can separate the your javascript into a .js file in assets folder, and then import it back with url filter.