· laravel · 2 min read

Install and use NPM packages in Laravel with Livewire/Blade

Are you like me and you need to use some NPM Package in your PHP project?

This is probably something super common for pro Laravel users, but for me… coming from the JavaScript world and learning PHP took me 20 minutes of searching and a headache :)

So, let’s write an article about it, so the next guy will take only 15 minutes, and the next one will write an article, and then the next one will take only 10 minutes… until ChatGPT gives us a good answer directly :)

Step 1: Choose an NPM Package

For simplicity’s sake, I’m going with js-confetti.

npm install js-confetti

Execute this command in your root folder, where you have the package.json file (check out the image for a quick visual guide, so the article isn’t too wordy!).

Target

Step 2: Register Your Package in app.js

Navigate to resources/js/app.js (or, for a quicker approach, use CMD+P and search for app.js).

Now, let’s add our NPM module:

import './bootstrap';

import JSConfetti from 'js-confetti';
window.JSConfetti = JSConfetti;

Step 3: Run the Vite Server

While this step isn’t too difficult, it’s easy to overlook when your website is running using Herd. To avoid forgetting it, execute the following command:

npm run dev

Step 4: Import the JS via vite() Directive

Ensure you have the vite directive in the head tag of your “component”:

@vite(['resources/css/app.css', 'resources/js/app.js'])

(Note: The inclusion of app.css is not necessary for executing JS, but it’s included by default.)

Typically, you’ll use a layout and then incorporate your JS in your component. If you create a new layout and forget to import this, issues may arise. Keep an eye out for potential pitfalls!

Step 5: Let’s make some Confetti!

Yay

-- your php or html --

<script language="JavaScript" type="module">
  const jsConfetti = new window.JSConfetti();
  jsConfetti.addConfetti();
</script>

Impressive right?

Before you celebrate, remember to include type=“module”; otherwise, it won’t work. And here’s a quick tip: the language=“JavaScript” attribute isn’t necessary and can be removed.

Summary

Ensure you haven’t missed any of these steps, or it won’t work as expected. If there’s an error, it might appear in your logs like this:

Uncaught TypeError: window.JSConfetti is not a constructor

This error occurs because it’s not defined, which can be confusing for new developers. Double-check your implementation to avoid this hiccup!

Did I miss something, or are you encountering any issues? Feel free to share your thoughts in the comments section! 😊

Back to Blog