0

I'm really beginner in twig and webpack.

I install some packages with yarn and use them inside app.js, but for some reasons I need some method of that packages inside of my twig files. when I try to call a function, get error.

for example I install boostrap-select package and require that in app.js

// app.js

var $ = require('jquery');

require('bootstrap/dist/js/bootstrap');
require('bootstrap-select/dist/js/bootstrap-select');

$(document).ready(function () {

    $('.selectpicker').selectpicker({});
})(jQuery);

everything is fine and work perfect but when call this package function inside of twig file like this

{% block javascripts %}
    <script type="text/javascript" src="{{ asset('b/app.js') }}"></script>
    <script>
        $('.selectpicker').selectpicker({});
    </script>
{% endblock %}

I get error.

Uncaught TypeError: $(...).selectpicker is not a function

after search in google for one day I found out can not do that ... and I must do some extra things ... every examples are around of jQuery.

what about other packages? how define a function from yarn packages globally and use that in twig file.

I try all of this solutions but not work for me

funtionName = require('package path')
window.functionName =  functionName;
global.funtionNmae = functionName;

anyone has any solutions, I just need call a function in twig :(.

1 Answer 1

2

"This error happens when your code (or some library that you are using) expects $ or jQuery to be a global variable. But, when you use Webpack and require('jquery'), no global variables are set."

Symfony Frontend - FAQ and Common Issues

jQuery and Legacy Applications

// app.js
var $ = require('jquery');
// ...
global.$ = global.jQuery = $;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, but my problem is not about $ or jQuery, jQuery is work fine and I set $ globally, my problem is about any other npm package, like bootstrap-select or my own javascript npm package, how you use function of another packages in your project?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.