How to use npm installed package in laravel application?

Viewed 14878

I want to use select2 package in my laravel 5 application.

I installed it using npm install select2 and also ran npm run dev. It appears in my node_modules folder.

But how do I actually refer to the files - js and scss of select2 package in my app.blade.php ?

2 Answers

Run npm run watch , because keeps track of all changes in .js.

In app.js add

require('select2/dist/js/select2');

In app.blade.php example:

<div>            
   <select class="js-select2 css-select2-50">
                    <option>1</option>
   </select>
</div>

I suggest an answer to this thread because it isn't marked as resolved and despite the answer given it didn't allow me to resolve the issue as of the time of reading this.


Resources


I have since found a functional solution of which here are the details in relation to the question of the OP. Verified and working with Laravel 8

  1. Install package via npm

    npm install select2
    
  2. Edit /resources/js/app.js to import javascript from package

    require('./bootstrap');
    
    /* ... */
    require('select2');  // Add this
    /* ... */
    
    Alpine.start();
    
  3. Edit /resources/css/app.css to import styles from package

    /* ... */
    @import 'select2'; // Add this
    
  4. Edit /resources/js/bootstrap.js to enable the use of .select2();

    window._ = require('lodash');
    /* ... */
    window.select2 = require('select2'); // Add this
    
  5. Run NPM

    npm run dev
    npm run watch
    
  6. NPM result in my case

Laravel Mix v6.0.39
āœ” Compiled Successfully in 2982ms

√ Mix: Compiled successfully in 3.05s
webpack compiled successfully


Testing

According to configuration documentation

HTML

<input type="text" class="form-control js-example-basic-single">

JS

<script type="text/javascript">
  $(document).ready(function () {

    $('.js-example-basic-single').select2({
      placeholder: 'Select2 testing purpose'
    });

  });
</script>

Render

enter image description here

Related