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

Executing a custom node module in script commands specified in package.json file

I created a node package called my-module which functions properly. When I add this module to a larger project, I would like it to be executed through the packege.json file. Here is how it currently works: "scripts": { "myModule" : "node ./node_modul ...

Attempting to showcase information in React

Having recently delved into React, I am attempting to display data (within a bootstrap modal) from MongoDB to React using an axios ajax request. Postman indicates everything is correct. However, React throws an error stating "TypeError: this.state.reviews. ...

Create an HTTP-only cookie from the resolver function in Apollo GraphQL

My objective is to pass the 'res' from my context into a resolver in order to utilize 'context.res.cookie' within my signin function and send an http only cookie. Although my sign-in function works fine, I am unable to see the cookie ad ...

What is the best way to activate a click event when I set a radio button to checked?

I am facing an issue with an uninitialized property in my app.component.ts: color!:string; I am trying to automatically initialize the color property when a radio button is selected: <div> <input type="radio" name="colors" ( ...

I keep encountering a 'Missing Permissions' issue whenever I attempt to execute the ban command in Discord.js. What could be causing this problem?

While working on coding a ban command for my Discord server, I encountered an issue where the command was not working as expected. Upon testing, I received an error message on the console stating DiscordAPIError[50013]: Missing Permissions. This was puzzli ...

What is causing my button to act in this way?

Initially, the website redirects to an undefined URL and then to test.com. I am looking for a way to implement a redirection sequence from to and finally to <head> <script type="text/javascript"> <!-- function popup(url ...

Exploring the World of Html

I'm struggling with an HTML problem related to a web programming class I'm taking. The assignment involves creating a video game using HTML and JavaScript, where an image moves randomly on the screen and the player must click on it as many times ...

In-line Vertical Ticker Display

I attempted to use vTicker, but I found that it does not function properly when used as an inline element. <h1> <div id="vticker"><ul>...</ul></div> Some other headline text </h1> My goal is to have the vertica ...

What is the best method for looping through a JavaScript object in cases where the value itself is an object?

Updated query. Thanks to @WiktorZychla for sparking my Monday morning thoughts on recursion. The revised code is functioning correctly now. Assuming I have a dummy object structured like this: const dummy = { a: 1, b: 2, c: { d: 3, ...

Get the hash value after a specific character using Javascript

I'm currently working on a website with ajax functionality where pages load when clicking on navigation buttons. However, I encounter issues when reloading the page as it defaults back to loading main.html, regardless of the URL. The hash being used i ...

Encountered an error while attempting to log in: TypeError: the property 'id' of null cannot be read

I am facing an issue with the login process, specifically getting a TypeError: Cannot read property 'id' of null error message. How can I debug and resolve this error? var cas = require('cas-client'); get_forward_url(function(forwardur ...

My Angular Router is creating duplicate instances of my route components

I have captured screenshots of the application: https://ibb.co/NmnSPNr and https://ibb.co/C0nwG4D info.component.ts / The Info component is a child component of the Item component, displayed when a specific link is routed to. export class InfoComponent imp ...

Effortlessly transforming a massive JSON into an Array using ReactJS

I have a large JSON dataset containing information on over 2000 cities. I want to use this data in my React app, but first I need to convert it into an array. A similar question has been asked before, but I couldn't find any answers that fit my specif ...

JavaScript, detecting repeated characters

I need to create a script that checks an input box (password) for the occurrence of the same character appearing twice. This script should work alongside existing regex validation. I believe I will need to use a loop to check if any character appears twice ...

I am looking to manage the error handling service, and my next step is to intentionally insert a single error into my service and have it automated

Need help with error handling in my service. I want to manually insert a single error, but would like it to be done automatically instead. 'use strict'; angular.module('nexoolApp.errorservice', ['nexoolApp.config']) .servic ...

Despite encountering Error 404 with AJAX XHR, the request is successfully reaching the Spring Controller

I am attempting to upload a file with a progress bar feature. var fileInput = document.getElementById('jquery-ajax-single') var form = new FormData(); form.append('uploadFile',fileInput.files[0]); $.ajax({ url: "fi ...

Under specific circumstances, it is not possible to reset a property in vue.js

In Vue.js, I have developed a 'mini-game' that allows players to 'fight'. After someone 'dies', the game declares the winner and prompts if you want to play again. However, I am facing an issue where resetting the health of bo ...

Issue encountered during the installation of Cordova

When trying to install Cordova, I encountered an error. I am not connected through a proxy; instead, I am using a dongle for internet access. ...

Issue encountered: Unable to load resource - ajax file upload failed due to net::ERR_SSL_BAD_RECORD_MAC_ALERT error

I've implemented an AJAX form file upload using jQuery. After testing my code across multiple computers and browsers, I've encountered an issue on one Windows 8 machine running Chrome where the upload functionality fails with the following error ...

Does vuetify have a v-autocomplete callback for when there is no filtered data available?

Is there a method to detect when the v-autocomplete component in Vuetify.js displays "no data available" after filtering? I have searched the events documentation here https://vuetifyjs.com/en/api/v-autocomplete/#events Is there a workaround for this iss ...