简体   繁体   English

Symfony4:Webpack Encore:在另一个js文件中调用js文件的功能

[英]Symfony4 : Webpack Encore : calling a function of a js file in another js file

I can't figure out how to manage multiple js files with Webpack Encore in Symfony. 我不知道如何使用Symfony中的Webpack Encore管理多个js文件。 I know that we can call functions and variables of a js file in another js file, simply without using Webpack and putting declaration of scripts tags in certain order but it doesn't work with webpack. 我知道我们可以在另一个js文件中调用一个js文件的函数和变量,而无需使用Webpack并按一定顺序放置scripts标签的声明,但这不适用于webpack。 How to configure that ? 如何配置呢?

The thing with using Encore in Symfony for JS, it wraps the files it builds in a function, thus obscuring them from the global scope. 在Symfony for JS中使用Encore可以将其生成的文件包装在一个函数中,从而将它们从全局范围中排除。 Therefore if you build your scripts using Encore, their functions and variables cannot be called directly from tags. 因此,如果使用Encore构建脚本,则不能直接从标签中调用其功能和变量。

However, you can call functions of other files/plugins from your custom JS file which was built with Encore, it's just a matter of requiring them in the script first. 但是,您可以从使用Encore构建的自定义JS文件中调用其他文件/插件的功能,只需在脚本中首先要求它们即可。

For example, I have this plugin called toastr and I want to call it from my script file. 例如,我有一个名为toastr的插件,我想从我的脚本文件中调用它。 The plugin is built as a vendor with Encore and my script is added as a simple entry: 该插件是使用Encore作为供应商构建的,并且我的脚本作为简单条目添加:

// webpack.config.js
// ...
Encore
    .createSharedEntry('vendor', [
        'toastr'
    ])
    .addEntry('myscript', './assets/js/myscript.js');

Then I can request 'toastr' in my custom script and use its functions like this: 然后,我可以在自定义脚本中请求“ toastr”并使用其功能,如下所示:

// assets/js/myscript.js
var toastr = require('toastr');

toastr.success('Hello!');

This example is with vendor a plugin, if you need two custom files it will be very similar, you just have to require your own file instead of a vendor plugin. 此示例带有供应商插件,如果您需要两个自定义文件,它将非常相似,您只需要使用自己的文件即可,而不是供应商插件。

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

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