How import a external js library in laravel?

I’ve downloaded a base template from this GitHub Repo based on the following dashboard gentella.

I install the inputmask library with the following command:

npm install inputmask --save

But reading and reading, I’m not sure which is the correct step to integrate the same into an HTML page, I read about mix, saas, Compiling Assets (Laravel Mix).

I try with this:

<script type="text/javascript" src="{{ URL::asset('js/inputmaskpath.js') }}"></script>

and this:

@section('scripts')
    {{ Html::script(mix('assets/js/inputmask.js')) }}
@endsection

The question finally is, how import inputmask into my HTML page and what it is the correct path?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

When you use npm to download packages, they will be downloaded in node_modules folder and they are not (directly) included/loaded into your project.

You use Laravel Mix to handle the assets compilation. So in your scenario you could handle it as the following:

First of all create a javascript file in resources/assets/js called app.js. Add the following code to be able to load the downloaded package

require('inputmask');

Then using Laravel mix you can compile app.js to produce for you one javascript file. Modify webpack.mix.js in your Laravel root folder to the following

mix.js('./resources/assets/js/app.js', 'public/js/app.js');

Now in your view you could load the javascript file as the following

<script src="{!! mix('js/app.js') !!}"></script>

So, in case of another downloaded package, you install it with npm first, then in your resources/assets/js/app.js file you require that package. Then Laravel mix will take care of combining all required packages into one javascript file.

I suggest you read this documentation for more information about Laravel Mix. This tutorial is useful also.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply