The JavaScript in the Laravel file isn't functioning properly, but it works perfectly when incorporated via CDN

Successfully implemented code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>

<script type="text/javascript">
var textWrapper = document.querySelector('.ml6 .letters');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");

anime.timeline({loop: false})
    .add({
    targets: '.ml6 .letter',
    translateY: ["1.1em", 0],
    translateZ: 0,
    duration: 750,
    delay: (el, i) => 50 * i
});
</script>

However, when I include the identical JavaScript from the CDN in libraries.js as demonstrated below, it results in a

ReferenceError: Can't find variable: anime
.

<script src="{{ mix('/js/libraries.js') }}"></script>

<script type="text/javascript">
var textWrapper = document.querySelector('.ml6 .letters');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");

anime.timeline({loop: false})
    .add({
    targets: '.ml6 .letter',
    translateY: ["1.1em", 0],
    translateZ: 0,
    duration: 750,
    delay: (el, i) => 50 * i
});
</script>

Upon verification, mix is compiling correctly, and the JS is included in libraries.js.

The script remains unchanged, positioned in the same location; however, I am puzzled by why this issue persists. Might it be due to libraries.js loading after the script executes? If so, how can this be resolved?

This problem recurs frequently. My preference is to utilize mix() over asset(). While the aforementioned addresses one library, my goal is to consolidate most of the libraries into a single file like libraries.js. Presently, many are loaded through CDNs due to the previously explained dilemma.

Answer №1

Assuming that you have a file named resources/js/libraries.js, filled with require(); statements to import packages from npm, along with another JS file importing custom code, here's a suggestion:

You can consolidate these imports without needing a separate JS file by utilizing webpack like so:

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')
    .extract([
        'bootstrap', 
        'popper.js',
        'lodash',
        'axios',
        'jquery',
        'vue',
    ]);

mix.version();

Then simply add this at the bottom of your layout:

<script src="{{ mix('js/manifest.js') }}"></script>
<script src="{{ mix('js/vendor.js') }}"></script>
<script src="{{ mix('js/app.js') }}"></script>
@stack('scripts')

vendor.js essentially replaces your libraries.js, while app.js contains your custom code.

By using mix.version(): If updates are made to your custom code and you run npm run prod, only app.js will be modified (a smaller JS file), leaving vendor.js (larger file) unaffected. This results in faster loading times as returning users will only need to load the minimal app.js, while the cached vendor.js remains unchanged.


To specifically address your issue, if the variable name anime is not being detected, ensure it is imported correctly in your JS file like this:

window.anime = require('animejs');

Answer №2

Execute the command npm run watch and give it another shot.

Answer №3

Perhaps this solution could be of assistance.

  1. I made sure to save the JavaScript file as .min.js.
  2. Instead of utilizing mix, I opted for asset to retrieve the JavaScript file.
<script src = "{{asset('js/anime.min.js')}}" type ="text/javascript"> </script>

Please verify this. No issues were detected during my examination.

The following is the full code that was tested:

<script src = "{{asset('js/anime.min.js')}}" type ="text/javascript">
</script>
  <script>
  var textWrapper = document.querySelector('.ml6 .letters');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");

anime.timeline({loop: false})
    .add({
    targets: '.ml6 .letter',
    translateY: ["1.1em", 0],
    translateZ: 0,
    duration: 750,
    delay: (el, i) => 50 * i
}).add({
    targets: '.ml6',
    opacity: 0,
    duration: 1000,
    easing: "easeOutExpo",
    delay: 1000
});
</script>

Answer №4

Consider encapsulating your inline javascript like so:

window.onload = function(){ // your code here };

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

"Enhancing Forms with Multiple Event Listeners for Seamless Sub

I'm working on creating a countdown timer with 3 buttons for controlling the timer: start, cancel, and pause. The timer itself is a text input field where you can enter a positive integer. I need to use core JavaScript, not jQuery Start Button: Init ...

`Developing reusable TypeScript code for both Node.js and Vue.js`

I'm struggling to figure out the solution for my current setup. Here are the details: Node.js 16.1.x Vue.js 3.x TypeScript 4.2.4 This is how my directory structure looks: Root (Node.js server) shared MySharedFile.ts ui (Vue.js code) MySharedFi ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

Having trouble with GLB file loading in three.js?

My GLB file is not displaying in my Three.js world. Despite following all the documentation and tutorials, the model is not showing up. The world loads perfectly and everything works fine, except for the model not appearing. I am on a journey to create a ...

Express.js and gridfs-stream are unable to retrieve the error

Imagine an effortless image download server where Express.js takes the request, fetches an image from MongoDB GridFS, and serves it as a response. Everything works fine when the request is valid and the file exists. The issue arises when it fails to catc ...

The declaration for "Control" is not present, possibly being restricted by its protection level

I'm really struggling to get the jQuery datepicker working in ASP.NET. I've tried various examples, but nothing seems to work for me. Even though I'm fairly new to ASP.NET, I am learning quickly! Here is the script I am trying to use: < ...

My function invocations seem to be malfunctioning

Originally, I wrote code without using functions to prototype and it worked perfectly fine: $(function() { $(".PortfolioFade img") .mouseover(function() { popup('PORTFOLIO'); var src = $(this).attr("src").rep ...

Error: The module '/@modules/vue.js' does not export a 'default' value as requested by the syntax

I'm encountering an issue with Vee Validate form validation in Vue.js. As a beginner, I am struggling to grasp the import syntax. After installing vee-validate using npm i vee-validate --save and placing it in my node_modules directory, I proceeded to ...

Using Angular 2 to pass a function as an argument to a constructor

How can I create a custom @Component factory where a function is called to return a component, passing the widgetName to the constructor or super constructor? export function createCustomKendoComponent(selector: string, **widgetName**: string) { @Co ...

Unable to integrate any modules or components from bit.dev into my React application

I am currently working on a React project and encountering an issue with importing a component from bit.dev. After installing the package via my terminal with the command: bit import nexxtway.react-rainbow/button You can find more information about it t ...

I'm having trouble with my dropdown navigation menus - they keep popping back up and I can't seem to access

My website is currently in development and can be accessed at: The top navigation bar on the homepage functions properly across all browsers. However, there are three sections with dropdown submenus - About Us, Training, and Careers. These dropdown submen ...

Creating a dropdown menu in Vue 3: A step-by-step guide

I've scoured the entire internet, but I still can't seem to resolve this issue. When using the code below, I keep getting an error message that says 'Uncaught ReferenceError: VueSelect is not defined.' Can you help me figure out what&ap ...

Steps for updating the property "project_id" within a nested JSON array to "project_name"

Issue: [ { "project_id": 1, "project_name": "CDP", "role": "PL" }, { "project_id": 2, "project_name": "Admincer", "role": "PM" }, I am trying to extract the "project_id" property from the above JSON array and add it to another array using a specific ...

Exploring the possibilities of accessing Vue.prototype within an .addEventListener function

I've been attempting to access the global object Vue.prototype.$firebase, which is declared in main.js. import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import VueTailwind from "vue- ...

Deactivating a Vue custom filter when hovering over it

I'm trying to figure out how to disable a truncate filter when hovering over an element using VueJS 2. Here's the part of my template that includes the filter: <div class="eng" @mouseover="showAll">{{ word.english | truncate }}</div> ...

Issue with AdminLite 2.4.0 data table functionality malfunctioning

Check out this template that I'm using. I've copied all the contents for the bower_components and dist folders, and made sure to link and require everything properly. There are no 404 errors, only status code 200. Here is a snippet of my code: ...

Troubleshooting resizing images in React using Material UI's useStyles

When attempting to resize an image using React, I am encountering a problem where adjusting the height and width of the tag with useStyles does not reduce the size of the image but instead moves it around on the page. Here is the code snippet: import { ma ...

Unique option preservation on customized HTML select menus - Maintain original selection

Currently, I am attempting to replicate a custom HTML select based on the example provided by W3 Schools. You can view the demo through this link: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select The issue I am encountering is that ...

What could be causing me to receive 'undefined' and an empty array[] when using Promise.all with JavaScript async operations making calls to Azure APIs?

In my personal project utilizing Azure AI APIs and Node.js/Express,, I am working on handling a get request to a /viewText route by extracting text and key phrases from an uploaded image/document. Below is the code snippet that should log this data to the ...

Please explain this ES6 syntax to me: Using a colon after a function call

While exploring the documentation for a flux store in React, I came across an example that caught my attention. import {ReduceStore} from 'flux/utils'; class CounterStore extends ReduceStore<number> { getInitialState(): number { ret ...