Search code examples
javascriptsymfonywebpacksymfony4webpack-encore

Loading an asset within the app.js Symfony 4 file


I'm looking to mainstream a certain asset loading within app.js

My assets get built like such: public/build/images/icons/**.svg

Within my app.js file, I have the following:

/*
* Welcome to your app's main JavaScript file!
 *
 * We recommend including the built version of this JavaScript file
 * (and its CSS file) in your base layout (base.html.twig).
 */

// any CSS you require will output into a single css file (app.css in this case)
import '../sass/standards.scss';

// Need jQuery? Install it with "yarn add jquery", then uncomment to require it.
const $ = require('jquery');

$(window).on("load", function() {
    $(".icon").each(function(){
        var $classes = $(this).prop("classList");

        var className;

        $.each($classes, function(){
            if(this.match("^icon-"))
            {
                className = this;
                return;
            }
        });

        className = String(className);
        var fileName = className.replace("icon-", "") + ".svg";

        $(this).load("public/build/images/icons/" + fileName);
    })
});

The idea is to find any .icon element and inject it with the appropriate SVG file that I have in the assets folder. But the problem is, there is also some caching happening so the file names change for version controlling. Is this the correct way to call an asset through the app.js file?

What's the proper way?


Solution

  • You need to require the file before using it. Docs.

    // assets/js/app.js
    
    // returns the final, public path to this file
    // path is relative to this file - e.g. assets/images/logo.png
    const logoPath = require('../images/logo.png');
    
    var html = `<img src="${logoPath}">`;