简体   繁体   English

Symfony + Webpack 在模板中使用节点包

[英]Symfony + Webpack using node packages inside templates

I am trying to implement Webpack Encore in my Symfony Project.我正在尝试在我的 Symfony 项目中实现 Webpack Encore。 I just added SweetAlert2 with node ( npm i sweetalert2 --dev ).我刚刚添加了SweetAlert2和节点( npm i sweetalert2 --dev )。

My "problem" is that I don't realize how to properly use this package once installed.我的“问题”是我没有意识到如何在安装后正确使用这个 package。 I've been reading other questions but I don't understand where do I need to import it.我一直在阅读其他问题,但我不明白我需要在哪里导入它。

So far I've tried:到目前为止,我已经尝试过:

  1. Creating a file inside /assets/js/swal.js ./assets/js/swal.js中创建一个文件。 Also, I have tried with ES5 as well:另外,我也尝试过使用 ES5:
import Swal from 'sweetalert2';

export const swal = (message, type) => {
    Swal.fire({
        position: 'top-end',
        icon: type,
        title: message,
        showConfirmButton: false,
        timer: 1500
    });
}
  1. Add it to webpack.config.js as an Entry Point:将其添加到webpack.config.js作为入口点:
.addEntry('app', './assets/js/app.js')
.addEntry('swal', '/assets/js/swal.js')
  1. Add it as an asset to the template with <script src="{{ asset('js/swal.js') }}"></script> .使用<script src="{{ asset('js/swal.js') }}"></script>将其作为资产添加到模板中。 Maybe is worth to mention that I did try all the paths and PHPStorm does not recognize any of them.也许值得一提的是,我确实尝试了所有路径,但 PHPStorm 无法识别其中任何一个。

  2. Print the function or class inside Twig template:在 Twig 模板中打印 function 或 class :

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>
        {% block stylesheets %}{% endblock %}

        {{ encore_entry_link_tags('app') }}
    </head>
    <body>
        {% block body %}{% endblock %}

        {{ encore_entry_script_tags('app') }}
        {% block javascripts %}{% endblock %}

        {% if app.flashes is not empty %}
            <script>
                console.log(swal);
            </script>
        {% endif %}
    </body>
</html>

I also tried importing it with require() but require is not idefined.我也尝试使用require()导入它,但require没有定义。

What should I do to implement this function and render it in the Twig template?我应该怎么做才能实现这个 function 并在 Twig 模板中呈现它?

You can only import modules inside javascript (or typescript, etc) files.您只能在 javascript(或 typescript 等)文件中导入模块。

let's say you have a function inside the script of the twig template:假设您在 twig 模板的脚本中有一个 function :

<script>
  function doSomethingBasic() {
     // do your thing here, then alert the user using Swal
  }
</script>

What you should do is export everything inside the javascript tag into a new.js file, inside the /assets folder.您应该做的是将 javascript 标记内的所有内容导出到 /assets 文件夹内的 new.js 文件中。

After you create a new file inside the /assets folder with any name you want, you should add that entry to the webpack.config.js.在 /assets 文件夹中创建具有所需名称的新文件后,应将该条目添加到 webpack.config.js。

For example: You created the newJavascript.js inside /assets.例如:您在 /assets 中创建了 newJavascript.js。

Inside webpack.config.js:在 webpack.config.js 内部:

.addEntry(`literallyAnyName`, `/assets/newJavascript.js`)

Then, in your twig template, substitute your script tags for this (must be the name you put in the webpack.config.js, in this case literallyAnyName):然后,在您的 twig 模板中,替换您的脚本标签(必须是您在 webpack.config.js 中输入的名称,在本例中为字面意思是 AnyName):

{{ encore_entry_script_tags('literallyAnyName') }}

With this, you can import Swal in your newJavascript.js有了这个,你可以在你的 newJavascript.js 中导入 Swal

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>
        {% block stylesheets %}
          {{ encore_entry_link_tags('literallyAnyName') }}
        {% endblock %}
    </head>
    <body>
        {% block body %}{% endblock %}

        {% set flashes = [] %}
        {% if app.flashes is not empty %}
          {% for label,message in app.flashes %}
             {% set flashes = flashes|merge([{
               'type': label,
               'message': message
             }]) %}
          {% endfor %}
        {% endif %}
            <div id="flashes" data-flashes="{{ flashes|json_encode|e('html_attr') }}"></div>
        {% block javascripts %}
          {{ encore_entry_script_tags('literallyAnyName') }}
        {% endblock %}
    </body>
</html>

newJavascript.js: newJavascript.js:

const flashes = JSON.parse(document.querySelector(`#flashes`).dataset.flashes);

// Maybe reduce the flash object into one message using flashes.reduce;
if(flashes.length > 0) {

  const msg = flashes.reduce(/* your logic here */);

  Swal.fire({
    position: 'top-end',
    icon: type,
    title: msg,
    showConfirmButton: false,
    timer: 1500
  });

}

This will trigger the second the page loads.这将触发页面加载的第二个。 You can make a button trigger as well if you need to.如果需要,您也可以制作按钮触发器。

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

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