Reputation: 359
I can't figure out how to manage multiple js files with Webpack Encore in Symfony. 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. How to configure that ?
Upvotes: 1
Views: 2288
Reputation: 186
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. Therefore if you build your scripts using Encore, their functions and variables cannot be called directly from tags.
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.
For example, I have this plugin called toastr and I want to call it from my script file. The plugin is built as a vendor with Encore and my script is added as a simple entry:
// 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:
// 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.
Upvotes: 1