Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 639
Carlos Laspina Avatar asked Jul 16 '17 04:07

Carlos Laspina


People also ask

Where do I put JavaScript code in laravel?

Your compiled JavaScript will typically be placed in the public/js directory. The app. js file will load the resources/assets/js/bootstrap. js file which bootstraps and configures Vue, Vue Resource, jQuery, and all other JavaScript dependencies.

Where does laravel store js files?

There are 2 places where I can store javascripts: resources/assets/javascripts and public/js. If you put the files in resources/assets/javascripts, then should add gulp tasks to copy them into public/js folder so it will ultimately present into public/js folder .


1 Answers

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.

like image 114
Mohammed Isa Avatar answered Oct 07 '22 06:10

Mohammed Isa