Laravel

Install select2 via npm in Laravel 8

Hello everyone, in this article, we will see how we can install select2 using NPM in Laravel 8.Before moving forward let’s know a bit about NPM.

All about NPM

  1. The name npm (Node Package Manager) stems from when npm first was created as a package manager for Node.js.
  2. All npm packages are defined in files called package.json.
  3. The content of package.json must be written in JSON.
  4. At least two fields must be present in the definition file: name and version.
  5. npm can manage dependencies.
  6. npm can (in one command line) install all the dependencies of a project.

We will follow the below steps to install select2

  • Install Npm
  • Install Select2
  • Add Code in webpack
  • Add code in App.js
  • Compile the asset
  • Call the select2

Step:1 Install Npm

Open the command panel from your project root folder and enter the below command, it will node modules packages.

npm i

Step: 2 Install Select2

Now we will install select2 by using the below command

npm i select2

Step: 3 Add Code in webpack

We will need 2 files from DataTable to be compiled by Laravel Mix.

This is the default webpack.mix.js that ships with Laravel. We will include the javascript file into resources/js/app.js and css file into resources/sass/app.scss.

Add the below code in your webpack

const mix = require('laravel-mix'); 
mix.js('resources/js/app.js', 'public/js')    
.sass('resources/sass/app.scss', 'public/css');

Step:4 Add code in app.js

Add the below code in app.js to compile select2

require('select2');

Step: 5 Compile the asset

To compile the asset we can to it in two way the first way we can use npm run watch , if you want to regular changes in your app.js or app.css file, second way when you are done with your changes and want’s to go for production then use npm run prod. You can use either of them to see the changes.

npm run prod
npm run watch

Step: 6 Call the select2

Now we have the select2 package compiled into app.js which you be found in your public folder.

The last part is to call the .select2() function.

Note: don’t add the below code in your head to call select2

<script>
   $(".js-example-basic-multiple").select2({
            multiple: true,
            tags: true,
        });
</script>

Result

select via npm

If you confusion feel free to comment, please rate me 5 if your like the post

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button