What is the correct way to use javascript (with dependencies) in a Laravel package (5.4)?

I have created some functionality in my Laravel 5.4 project which I think will be useful in other projects. To make it reusable I implemented it as a Laravel package (the following instructions are here: https://laravel.com/docs/5.4/packages )

The package defines some views, and the views require some javascript and that javascript requires jQuery.

So how can I set things up so that scripts are executed when my views are rendered?

The Laravel documentation describes how to use the vendor method publish()

so that package scripts are copied to the public directory ( https://laravel.com/docs/5.4/packages#public-assets ). But does this assume that the scripts are already compiled / minified? And once they are in the public directory, how are we supposed to download them? And how do we handle script dependencies (jQuery in my case)? We don't want it to turn on more than once.

And where does this Laravel Mix come in this?

I think ideally we should be able to put the javascript source code somewhere in the package:

require('jquery');
// do things with jquery

      

Then when I run npm run dev

(or npm run production

) the javascript of the package is compiled by Mix along with the javascript of the application and all their dependencies, and the end user's browser just needs to load app.js.

Can anyone suggest how to do this?

Or if I do it all wrong, then can anyone suggest how to do it "right"?

+3


source to share





All Articles