简体   繁体   English

在 app.js Symfony 4 文件中加载资产

[英]Loading an asset within the app.js Symfony 4 file

I'm looking to mainstream a certain asset loading within app.js我希望在 app.js 中主流化某些资产加载

My assets get built like such: public/build/images/icons/**.svg我的资产是这样构建的: public/build/images/icons/**.svg

Within my app.js file, I have the following:在我的 app.js 文件中,我有以下内容:

/*
* 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.这个想法是找到任何.icon元素并将其注入到 assets 文件夹中的适当 SVG 文件中。 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?这是通过 app.js 文件调用资产的正确方法吗?

What's the proper way?什么是正确的方法?

You need to require the file before using it.您需要在使用之前require该文件。 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}">`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM