Utilizing an npm Package in Laravel - Dealing with ReferenceError

I'm having trouble with the installation and usage of a JS package through npm. The package can be found at .

First, I executed the npm command:

npm install --save zenorocha/clipboardjs

Next, I added the following line to my app.js file:

require('clipboard');

Afterward, I ran:

npm run dev 

Unfortunately, I'm stuck now and unsure how to properly load the package!

Each time, I encounter this error message:

ReferenceError: Can't find variable: ClipboardJS

Your help in resolving this issue would be greatly appreciated! Thank you, Nic

PS: Just for clarity, all I have done is execute the npm install command and added a line to the app.js file. Is there something else that needs to be done?

Answer №1

Similar to the previous answer, initializing ClipboardJS with

window.ClipboardJS = require('clipboard');
is the initial step you must take. However, when incorporating it into your blade template, ensure that you enclose your code within a ClipboardJS object inside this specific event handler

https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event

<script>
    document.addEventListener('DOMContentLoaded', () => {
      // insert your ClipboardJS code here
    });
</script>

Answer №2

To ensure it works, you might want to assign it to the window object.

Instead of using

require('clipboard');

try this:

window.ClipboardJS = require('clipboard');

After following these steps in a fresh Laravel project, I was able to get it working smoothly.

Answer №3

If you encounter any issues while adding the Clipboardjs package in Laravel 10, follow these steps:

Package Installation-

Install the clipboardjs via npm -

npm install clipboard --save

Verify if the package is included in package.json -

cat package.json

The dependency should be listed there.

{
  "dependencies": {
    "clipboard": "^2.0.11"
  }
}

Once confirmed that the package is installed and accessible in your Laravel app, proceed to initialize it.

Import Clipboard in resources/js/app.js -

In resources/js/app.js, import the ClipboardJS class from the clipboard package.

import ClipboardJS from 'clipboard';

Instantiate ClipboardJS class in resources/js/app.js -

In resources/js/app.js, create an instance of the ClipboardJS class from the clipboard package.

new ClipboardJS('#copyToKeyboard');

Here, copyToKeyboard refers to the id of the copy button to be clicked.

Using Clipboard in Blade file-

Add copy button and target element in your Laravel blade -

<input type="text" readonly id="slug" name="slug">
<span id="copyToKeyboard" data-clipboard-target="#slug">Copy</span>

[!NOTE]
The id="copyToKeyboard" corresponds to the element for which we instantiated the ClipboardJS class.

[!NOTE]
The

data-clipboard-target="#slug"
represents the id of the target element whose value will be copied.

[!IMPORTANT]
Don't forget to include

@vite(['resources/css/app.css', 'resources/js/app.js'])
in your app.blade.php or parent blade layout to automatically build the js and css using the vite server.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Uncovering components generated by React JS with BeautifulSoup

My goal is to extract anchor links with the class "_1UoZlX" from the search results on a specific page - After analyzing the page, I realized that the search results are dynamically generated by React JS and not readily available in the page source or HTM ...

Error encountered in Pokemon API: Trying to access property '0' of undefined

My current challenge involves accessing the abilities of my Pokemon, but I keep encountering a recurring error. In my project development using React hooks, I fetched data from the Pokemon API and stored it in setWildPokemon. Utilizing wildPokemon.name suc ...

Attempting to showcase the data stored within MongoDB documents on my website's user interface

I am facing difficulties in showing the data stored in my database on the front end of my grocery list app, which is built using the MERN stack. I have a form that successfully sends data to MongoDB and saves it upon submission. In order to retrieve the d ...

Begin counting starting from 1 all the way up to 24, then feel free

I've developed a counter that increments from 0 to 24, and once it reaches 24: setInterval(function(){DayAndNight()}, 1000); var iState = 12; function DayAndNight() { //console.log('test'); switch(iState) ...

Determining when all $http requests have completed in AngularJS

After running multiple $http calls, I need to trigger an event only when all of them have been processed. Additionally, I must be informed if any call has failed along the way. Despite attempting solutions found on stackoverflow, such as using an intercept ...

Vertically align the left div in the center, while maintaining the standard alignment of the right div

I have been experimenting with Bootstrap 4 and attempting to implement the Vertical alignment feature as outlined on the webpage: https://getbootstrap.com/docs/4.0/layout/grid/ Despite reviewing my code multiple times, I am unable to identify the mistake ...

Identifying whether a Property in an Object is another Object

I'm planning to utilize JSON for stringifying the value of a property within an object, which will then be stored as a Tag on Google Calendar using Google Apps Script. The value in question is actually a double-nested Object (look at extraAttributes w ...

The error message at line 757 in utils.ts states that the [div] element is not recognized as a valid <Route> component

I've been trying to set up routes for Register and Login components inside a div with the className 'container' using react-router v6. However, whenever I try to access these components, I end up on a blank page. Strangely, when I remove the ...

JavaScript or Query: Transforming an Object from an Associative Array

Can someone help me out with converting an associative array into an object in JavaScript? I tried searching on Stackoverflow but couldn't find a working example. Here is the example structure: var combinedproducts = [["Testing-1","test-1"],["Testin ...

Can anyone suggest methods for displaying query data from a JSON file using HTML?

After countless hours of searching through various forums, I have attempted numerous methods to display query data from a JSON file onto an HTML page. My initial attempt was using XmlHttpRequest, which yielded no results. I then tried utilizing jQuery, sp ...

When attempting to view the PDF file, it appears completely void

After spending countless hours on this task, I'm still not making any progress. My goal is to download a PDF file from my server while currently running the operation on localhost. However, whenever I open the downloaded PDF, all I see is a blank whit ...

Ways to modify the pre-defined value in a TextField

I encountered a situation where I have a form with pre-filled data from a specific country. The data is initially read-only, but the user can click on the edit button if they wish to make changes. The issue arises when trying to edit the value in the Text ...

Why is the React Util js file not functioning properly when using an absolute path?

Help needed! I'm utilizing create-react-app without ejecting. I can't seem to figure out why this code snippet is not functioning correctly. import { capitalizeFirst } from 'util/util.js'; //This line is causing issues import AdminIn ...

Utilizing Selenium in Python to Scroll within Inner Div: A Guide

Curious about how to scroll through the chats on web.whatsapp.com? Check out the pseudo-code below: recentList = driver.find_elements_by_xpath("//div[@class='_2wP_Y']") driver.execute_script("window.scrollTo(0, 500);") I'm eager to find a ...

I need a layout similar to the navbar on http://thecoloradan.com/ but I am not asking for instructions on how to do it

Have you seen the stunning navbar on this website? It appears to merge with the background upon loading, then smoothly shifts to the top of the page as you scroll. The transition is accompanied by a lovely animation. I am curious about the steps needed to ...

Conceal YouTube upon opening any model or light box

I have a YouTube video in the center of my page, and when I click on any link from the side navigation, a lightbox appears. However, in IE, the lightbox is behind the YouTube video. I have tried setting the Z-index, but it doesn't seem to work. Is the ...

Customizing the appearance of a date input field by passing an object with Vue.js

I created a dynamic table using Vuejs, where each cell contains an input element set as readOnly initially. The table also includes an 'edit' button for each row, which, when clicked, changes to 'save' and allows editing of the input el ...

Tips for identifying the version of a package that is installed using a package-lock.json file containing lockfileVersion = 3

After upgrading from Node 16 (npm 8) to Node 18 (npm 9), I noticed a difference in the structure of the package-lock.json files. Files generated with npm 8 have a lockfileVersion: 2, while those generated with npm 9 have a lockfileVersion: 3. The changes a ...

Having trouble with running `npm start` on a computer that has different versions of Node and

I have encountered an issue with running a React application on two different computers. One computer, a MacBook, is running the app without any problems, while the other, an Ubuntu 18.04 machine, is having trouble starting it. Here are the configurations ...

When utilizing JqGrid, make sure to utilize the 'aftersavefunc' and 'successfunc' methods prior to executing the 'saveRow' function

After saving a row in order to retrieve the Id for logging, I am encountering an issue where 'aftersavefunc' and 'successfunc' are triggering 'reloadGrid('#telephoneGrid')' before the save operation. It seems that th ...