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

Viewed 125

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've implemented it as a Laravel Package (following instructions here: https://laravel.com/docs/5.4/packages)

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

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

The Laravel documentation describes how to use the service provider's publish() method in order to have package scripts copied to the public directory (https://laravel.com/docs/5.4/packages#public-assets). But does this assume the scripts are already compiled / minified? And once they're in the public directory, how should we load them? And how do we handle script dependencies (in my case jQuery)? We don't want it being included more than once.

And where does Laravel Mix come into this?

I think ideally we should to 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 package javascript is compiled by Mix along with the app javascript and all their dependencies, and the end user's browser just needs to download app.js.

Can anyone suggest how to accomplish this?

Or if I'm going about this all wrong, then can anyone suggest how to do this the 'right' way?

0 Answers
Related