Error: Laravel mix compilation - unable to locate class

After upgrading from Laravel 5.3 to 5.4, I am currently in the process of transitioning to webpack.

Although it compiles without errors, whenever I try to load the page, I always encounter:

app.a711192….js:125 Uncaught ReferenceError: Layout is not defined at HTMLDocument. (app.a711192….js:125) at i (vendor.19cd2ff….js:2) at Object.fireWith [as resolveWith] (vendor.19cd2ff….js:2) at Function.ready (vendor.19cd2ff….js:2) at HTMLDocument.J (vendor.19cd2ff….js:2)

I have checked the compiled app.js and noticed that Layout is included, but for some reason it's not loading correctly.

webpack.mix.js

const { mix } = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */
let npmFolder = './node_modules/';
mix.disableNotifications()
    .js('resources/assets/js/app.js', 'public/js')
    .scripts([
        npmFolder + 'jquery/dist/jquery.min.js',
        npmFolder + 'jquery-migrate/dist/jquery-migrate.min.js',
        npmFolder + 'bootstrap-sass/assets/javascripts/bootstrap.min.js',
        npmFolder + 'axios/dist/axios.min.js'
    ], 'public/js/vendor.js')
    .sass('resources/assets/sass/app.scss', 'public/css')
    .sass('resources/assets/sass/admin/admin.scss', 'public/css')
    .version()
;

app.js

require('./layout.js');
require('./main.js');

main.js

$(function()
{
    let instance = axios.create({
        baseURL: 'https://some-domain.com/api/',
        timeout: 1000,
        headers: {'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')}
    });

    let layout = new Layout();

    $("button[data-layout-action]").click(function(e)
    {
        let action = $(this).attr('data-layout-action');

        console.log(action);

        switch(action)
        {
            case 'new-page':
                layout.newPage();
                break;
            case 'edit-page':
                layout.editPage();
                break;
            default:
                alert('Invalid layout action ' + action)
        }
    });
});

layout.js

class Layout {
    constructor() {

    }

    newPage() {
        this.loadPage({});
    }

    editPage() {

    }

    loadPage(layout) {
        axios.post('/layout/generate', {
            layout
        })
            .catch(error => {
                alert(error);
            })
    }
}

Answer №1

After some trial and error, I was able to solve this puzzle by inserting the code below into Layout.js

module.exports = Layout;

Next, I implemented the following in app.js

import * as _layout from './Layout';

const Layout = new _layout();

Answer №2

It's been a while since I last used require, so I may be a bit out of practice. However, it seems like there might be a misunderstanding in how you are using require.

A couple of suggestions come to mind:

  1. Consider trying require('./layout.js') within main.js

  2. If the above suggestion doesn't work, you could try storing the require as a value. For example, instead of using new Layout();, try using

    let layout = require('./layout.js');

  3. If none of the previous suggestions help, you might want to look into how imports are done now, as that is the current standard.

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

Avoiding the Popover Component from Covering the Screen When the Menu Component Opens in React Material UI

I have implemented a Menu component to display a menu upon hovering over an element. However, I have encountered an issue where the menu includes a Popover component that opens up and covers the entire screen as an overlay, preventing interaction with th ...

Using JQuery to Execute Matching Based on Text Within <A> Elements

After reviewing the resources on Jquery Extract URL from Text and jquery match() variable interpolation - complex regexes, I am still a bit confused. The issue at hand is that I have a webpage with a dropdown menu at the top. Inside the dropdown, there ...

What does [] represent in the context of the [].forEach.call() method?

I'm a bit confused about the meaning of [] in the code snippet below. Is it just indicating the most recently declared array? Can someone provide clarification? In this particular example, we have two arrays named racersList and volunteersList stored ...

NPM-AUDIT has detected two critical vulnerabilities. What steps should I take next?

npm audit was run on my project and flagged the following vulnerability: High severity issue of Command Injection in a dependency of @angular-devkit/build-angular [dev] Vulnerable Path: @angular-devkit/build-angular > @ngtools/webpack > tree-kill ...

Using JavaScript, capture the current date and time and store it in a .txt file with the corresponding format

Objective: Upon clicking the download link, an automatically named file will be downloaded with today's date and time format. For example, 7-3-2021 04:04:00 PM or any applicable format with the date and time included in the name. Below is the code sn ...

Run PHP code using JavaScript

I am currently using Windows and attempting to use JavaScript/PHP to call a specific form that is saved in a different location. The file D:\Test\Form.php has the following content: <form action="D:\Test\submit.php" method="post"&g ...

Including a Javascript library (jsencrypt) in an Angular 2 application

I have gone through countless tutorials on this particular issue, but unfortunately, I have not yet found a solution. Let me provide some context first. I am working on an Angular 2 application and I need to incorporate this JS library for encryption: http ...

After the AJAX request, $this experienced a loss of focus

I am facing an issue with my CakePHP code snippet below: <tr class="tr_clone"> <td><?php echo $this->Form->input('items][',array('label'=>false,'options'=>$items,'class'=>'it ...

Attempting to retrieve dynamically generated input fields and cross-reference them with structured length .json data

In the process of developing code, I've implemented a for loop to dynamically generate HTML input fields based on the length of some data in a .json file. My goal is to use jQuery to compare the text entered in each input field with the corresponding ...

Varied approaches to managing responsive layouts

I am encountering an issue with the responsive design of a website I am currently developing. Scenario: The website features 3 different layouts for Desktop, Tablet, and mobile devices. These layouts consist of similar components with slight CSS adjustmen ...

Ways to include x-api-key in Angular API request headers

I am attempting to include the x-api-key header in the headers, as shown below: service.ts import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; import { Observable } from ...

Having issues making div elements with javascript

I am having trouble generating new divs when a specific div is clicked. Despite my efforts, nothing seems to be happening and the console isn't showing any errors. I've searched online for solutions but haven't found anything that addresses ...

Setting up Bootstrap 4 in Laravel 5.7

Currently, I am faced with the task of compiling my app.scss file for a new Laravel project. However, I am hoping to integrate Bootstrap 4 into the project instead of relying on the default Bootstrap that comes with Laravel. Unfortunately, when running npm ...

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

Combining ExtJS Paging with Dropdown Selection

Having an issue with a combo box created using the ExtJS framework. The pagination feature is not working correctly. Can anyone provide assistance with this? var store = new Ext.data.ArrayStore({ fields: ['id'], pageSize:1, data : ...

Different options for reading large files during an AJAX file upload

It seems that php's file_get_contents is not able to handle large files. What can be done as an alternative if it is causing a "stack overflow" issue? HTML File <form id='test'> <input type='file' name='Receipt&ap ...

Retrieving fresh CSS data from earlier animated elements within a Greensock timeline

In my code, I am using a TimelineLite() to perform a series of sequential tweens with .to(). What I want to achieve is accessing the output value from one of the early tweens in order to use it for constructing later tweens. Is there any way to retrieve t ...

Creating a responsive gallery using CSS techniques

I'm currently working on creating a simple gallery. My goal is to achieve the following design: https://i.sstatic.net/jq8pe.jpg However, the result I'm getting looks like this: https://i.sstatic.net/hSZyj.png The issue I'm facing is that ...

Navigating the NestJS @Get() Decorator: A Comprehensive Guide

The code snippet above demonstrates the functionality of accessing two different functions using URLs like http://localhost:3000/vehicle/availableVehicles and http://localhost:3000/vehicle/1. Both functions work properly in this setup. @Controller(&apo ...

Utilize Parse cloud code to navigate and interact with object relationships

I am currently in the process of developing a Parse cloud code function that will produce a similar outcome to a GET request on parse/classes/MyClass, but with the IDs of the relations included. While I have successfully implemented this for a single obje ...