Using laravel mix to include js dependencies

Viewed 7376

i can't really get my js libraries to work , some time ago i decided to have a separate js file for every library i use (so i have a jquery.js file and a bootstrap.js file included in my layout) ,everything was working just fine until i had to add jquery-ui to this chaos , and got this error

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

until i loaded ,jquery and jquery-ui in the same file .The problem is i dont want to include jquery ui everywhere i include jquery , beacuse i only use it in 2 pages. Below i will put my code :

jquery-ui.slider.js:

require('jquery-ui/ui/widgets/slider');
require('./components/carFilter.js');

app.js:

window.$ = window.jQuery = require('jquery');
require('./bootstrap');

webpack.mix.js:

mix.js('resources/assets/js/app.js', 'public/js')
mix.js('resources/assets/js/jquery-ui.slider.js', 'public/js');

I am using the following npm modules :

  • bootstrap-sass
  • jquery
  • jquery-ui
3 Answers

I think laravel-mix only serves the purpose when you have small sites with pages that all include the same app.js & app.css files.

When you have complex portal with multiple pages that have different set of frontend "plugins" you have to split your entries & generate a table of dependencies automatically.

After a lot of time searching I've come to the conclusion that the best approach would be switch to webpack-encore from Symfony.

You can read more about it's capabilities here Webpack Encore Official Documentation.

Now the question is how to embed it to Laravel? It's quite easy, I've just reverse engineered the Symfony's PHP bundle for that and here is the result: https://github.com/ntpages/laravel-encore

Now you just have to include you're dependency in the page entry and it's all handled automatically.

Related