0

I have installed big.js but still cannot access it from script tags within the different views in my application. I keep getting the following error: Uncaught ReferenceError: Big is not defined http://localhost/metre-readings/create?metred_input_id=1&read_at_filter=2021-11-08T23:00:1393

The following are the steps I took to implement big.js:

  1. installed big.js package by running: npm install big.js

  2. included package in app.js by adding const Big = require('big.js'); as follows:

const Big = require('big.js');

require('./bootstrap');

require('alpinejs');


let numberInputs = document.querySelectorAll('input[type="number"]');
numberInputs.forEach(numberInput => {
  numberInput.addEventListener('keypress', e => {
    let ASCIICode = (e.which) ? e.which : e.keyCode
    if (ASCIICode > 31 && (ASCIICode < 46 || ASCIICode > 57) || ASCIICode == 47)
      e.preventDefault();
    return true;
  });
});

function updateProducts() {
  document.querySelector('#vehicle_selection').submit();
}

  1. ran "npm run dev"

  2. included script in the app.blade.php component by adding <script src="{{ asset('js/app.js') }}" defer></script> as follows:


<!DOCTYPE html>
<html lang="en" class="" translate="no">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url('') }}">
    <!-- Styles -->
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">
    <!-- Font Awesome -->
    <script src="https://kit.fontawesome.com/ef96c5d743.js" crossorigin="anonymous"></script>
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>
    <!-- Chart js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js" integrity="sha512-R/QOHLpV1Ggq22vfDAWYOaMd5RopHrJNMxi8/lJu8Oihwi4Ho4BRFeiMiCefn9rasajKjnx9/fTQ/xkWnkDACg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <title>{{ config('app.name') }}</title>
  </head>

  <body class="font-body antialiased bg-gray-50 min-h-screen flex flex-col">
    <!-- Page Heading -->
    <header class="bg-gray-100 shadow-md z-10 h-10 w-full">
      <div class="bg-gray-100 p-2 shadow-md h-10">
        <div class="max-w-7xl text-center lg:flex justify-between md:items-center mx-auto">
          <x-hamburger />
          <h2 class="font-semibold text-lg text-gray-800 leading-tight">
            {{ $header }}
          </h2>
          <!-- User log out -->
          <form method="POST" action="{{ route('logout') }}" class="hidden lg:flex">
            @csrf
            <div class="text-sm">{{ auth()->user()->name }}</div>
            <a href="{{ route('users.create') }}" class="text-sm ml-1 text-primary-600"
              onclick="event.preventDefault(); this.closest('form').submit();">
              ({{ __('log out') }})
            </a>
          </form>
        </div>
      </div>    
    </header>

    <div class="flex-grow flex z-0">
      @include('layouts.navigation')
      
      <!-- Page Content -->
      <main class="flex-grow h-full">
        {{ $slot }}
      </main>
    </div>
  </body>

</html>

  1. tried to use Big class in one of the view blades (create.blade.php) which extends the app.blade.php component. I added the following code inside script tags console.log(new Big(1.0)); as follows:
<x-app-layout>
  <x-slot name="header">
    {{ __('Metre reading') }}
  </x-slot>

  <div class="bg-white shadow md:rounded-lg md:rounded-b-none mt-3 md:mt-6 max-w-3xl mx-auto">

    <div class="pt-3 md:pt-6 px-2 md:px-6">

      <x-session-status :status="session('status')" />
      <x-validation-errors :errors="$errors" />

      <p class="text-sm text-center font-medium text-red-600 mb-2">{{ __('Please make sure all production entries are up to date') }}</p>

      <!-- Metre reading type selection -->
      <form action="" method="GET" id="filter">
        <div class="flex mb-2">
          <label for="metred_input_id" class="inline-label whitespace-nowrap">{{ __('Input') }}</label>
          <select name="metred_input_id" id="metred_input_id" class="inline-input">
            <option value="">{{ __('Select type') }}</option>
            @foreach ($metredInputs as $metredInput)
              <option value="{{ $metredInput->id }}" @if ($metredInput->id === (int) request('metred_input_id')) selected @endif>{{ $metredInput->name }}</option>
            @endforeach
          </select>
        </div>

        <div class="flex mb-2">
          <label for="read_at_filter" class="inline-label whitespace-nowrap">{{ __('Time') }}</label>
          <input type="datetime-local" name="read_at_filter" id="read_at_filter" value="{{ request('read_at_filter', now()) }}"
                class="inline-input mr-2" step="60">
          <button id="date_based_data" class="btn-secondary rounded p-2">{{ __('Get') }}</button>
        </div>
      </form>
    </div>

    <!-- Main form -->
    <form action="{{ route('metre-readings.store') }}" method="POST" autcomplete="off">
      @csrf

      <div class="px-2 md:px-6">
        <!-- Metre reading type -->
        @php
          $selectedInput = request('metred_input_id') ? $metredInputs->find(request('metred_input_id')) : 0;
        @endphp

        <input type="hidden" name="metred_input_id" value="{{ request('metred_input_id', '') }}">

        <div class="px-2 border-4 bg-gray-50 mb-2 rounded">

          <div class="pt-1">
            <span class="font-medium">{{ __('Readings') }}</span>
            <span class="text-xxs">{{ $selectedInput ? '(' . $selectedInput->unit . ')' : '' }}</span>
          </div>
          <!-- PREVIOUS PERIOD READINGS -->
          <div class="w-full text-center bg-gray-100 mt-2 mb-2 border border-gray-700">
            <div class="text-sm p-1 font-medium">{{ __('Previous reading') }}</div>
          
          
            <div class="flex">
              <label for="latest_reading" class="inline-label whitespace-nowrap border-b-0 rounded-l-none w-1/3 text-left p-1 text-xs">{{ __('Reading') }}</label>
              <input type="number" name="latest_reading" id="latest_reading" step="any"
                      value="{{ $lastTwoReadings ? $lastTwoReadings->latest_reading : '' }}" class="inline-input readonly border-b-0 p-1 text-right text-xs" readonly>
            </div>
            <div class="flex">
              <label for="latest_reading_date" class="inline-label whitespace-nowrap rounded-l-none border-b-0 p-1 w-1/3 text-left text-xs">{{ __('Taken on') }}</label>
              <input type="text" name="latest_reading_date" id="latest_reading_date" step="any"
                      value="{{ $lastTwoReadings ? $lastTwoReadings->latest_reading_date->format('d-m-Y H:i') : '' }}" class="inline-input readonly border-b-0 text-right p-1 text-xs" readonly>
            </div>
            <div class="flex mb-2">
              <label for="previous_consumption_rate" class="inline-label rounded-l-none flex flex-col w-1/3 p-1 text-left text-xs">
                <span class="whitespace-nowrap leading-tight">{{ __('Rate') }}</span>
                <span class="text-xxs leading-tight">{{ $selectedInput ? '(' . $selectedInput->unit . ' / carton)' : '' }}</span>
              </label>
              <input type="text" name="previous_consumption_rate" id="previous_consumption_rate" step="any"
                      value="{{ $previousConsumptionRate ? $previousConsumptionRate : 'Not enough readings to calculate rate' }}" class="inline-input readonly text-right p-1 text-xs" readonly>
            </div>
          </div>

          <!-- Border separator --> 
          <div class="border-b border-gray-400 border-dashed mb-2"></div>

          <!-- CURRENT PERIOD READINGS -->
          <div class="w-full text-center bg-gray-100 mt-2 mb-2 border border-gray-700">
            <div class="text-sm p-1 font-medium">{{ __('Current reading') }}</div>

            <div class="flex mb-2">
              <label for="reading" class="inline-label whitespace-nowrap rounded-none w-1/3 text-left">{{ __('Reading') }}</label>
              <input type="number" name="reading" id="reading" step="any" value="{{ old('reading') }}" class="inline-input rounded-none text-right">
            </div>
            <div class="flex">
              <label for="production" class="inline-label flex flex-col border-b-0 rounded-none p-1 w-1/3 text-left text-xs">
                <span class="leading-tight">{{ __('Production') }} <span class="text-xxs">(cartons)</span></span>
              </label>
              <input type="text" name="production" id="production" step="any"
                      value="{{ $currentPeriodProduction }}" class="inline-input readonly p-1 border-b-0 text-xs text-right" readonly>
            </div>
            <div class="flex mb-2">
              <label for="current_consumption_rate" class="inline-label flex flex-col rounded-none p-1 w-1/3 text-left text-xs">
                <span class="leading-tight">{{ __('Rate') }}</span>
                <span class="text-xxs leading-tight">{{ $selectedInput ? '(' . $selectedInput->unit . ' / carton)' : '' }}</span>
              </label>
              <input type="text" name="current_consumption_rate" id="current_consumption_rate" step="any"
                      value="" class="inline-input readonly p-1 text-xs text-right" readonly>
            </div>
          </div>
        </div>

        <div class="flex">
          <label for="cash_payment_amount" class="inline-label">{{ __('Expense') }}</label>
          <input type="number" name="cash_payment_amount" id="cash_payment_amount" step="any"
                 value="{{ old('cash_payment_amount') }}" class="inline-input mr-2 text-right">
          <input type="number" id="cost_rate" class="readonly text-right" readonly>
        </div>
        <div class="text-xxs self-end mb-2 text-right">{{ $selectedInput ? 'JOD / ' . $selectedInput->unit : '' }}</div>

        <div class="flex mb-3 md:mb-6">
          <label for="periods" class="inline-label">{{ __('Period(s)') }}</label>
          <input id="periods" type="text" name="periods" class="inline-input" placeholder="mm-yyyy, mm-yyyy, mm-yyyy" autocomplete="off" value="{{ old('periods') }}">
        </div>

        <input type="hidden" name="read_at" id="read_at" value="{{ request('read_at_filter', now()) }}">

      </div>

      <div class="bg-gray-100 p-3 md:p-6 flex items-center justify-end">
        <button class="btn-primary rounded">{{ __('Pay') }}</button>
      </div>

    </form>   

  </div>

  <script>
    console.log(new Big(1.0));
    const METRED_INPUT = document.querySelector('select#metred_input_id');
    let lastTwoReadings = {!! json_encode($lastTwoReadings) !!};

    if (lastTwoReadings) {
      previousReading = lastTwoReadings.latest_reading;
    }
    
    const updateCostRate = () => {
      consumption = READING.value - previousReading;
      if (CASH_PAYMENT_AMOUNT.value > 0 && consumption > 0) {
         COST_RATE.value = CASH_PAYMENT_AMOUNT.value / consumption;
      } else {
        COST_RATE.value = '';
      }
    }

    METRED_INPUT.addEventListener('change', e => {
      e.target.parentElement.parentElement.submit();
    });

    const READING = document.querySelector('input#reading');
    const CURRENT_RATE = document.querySelector('input#current_consumption_rate');
    
    let currentPeriodProduction = {!! json_encode($currentPeriodProduction) !!};
    
    
    READING.addEventListener('keyup', e => {
      consumption = e.target.value - previousReading;
      if (!currentPeriodProduction) {
        CURRENT_RATE.value = 'No production during the period';
      } else if (consumption < 0) {
        CURRENT_RATE.value = 'Reading lower than previous one';
      } else {
        CURRENT_RATE.value = consumption / currentPeriodProduction;
      }
      updateCostRate();      
    });

    const READ_AT_FILTER = document.querySelector('input#read_at_filter');
    const DATE_BASED_DATA = document.querySelector('button#date_based_data');

    READ_AT_FILTER.addEventListener('change', e => {
      DATE_BASED_DATA.classList.add('bg-red-600', 'text-white');
    }); 

    const CASH_PAYMENT_AMOUNT = document.querySelector('input#cash_payment_amount')
    const COST_RATE = document.querySelector('input#cost_rate')

    CASH_PAYMENT_AMOUNT.addEventListener('keyup', e => {
      if (READING.value > 0) {
        updateCostRate();
      }
    });

  
  </script>

</x-app-layout>

I keep getting the following error whenever I hit the create.blade.php page

Uncaught ReferenceError: Big is not defined
<anonymous> http://localhost/metre-readings/create?metred_input_id=1&read_at_filter=2021-11-08T23:00:1393
Jose Lora
  • 1,392
  • 4
  • 12
  • 18
  • Check the root of the library ... sometimes you get linking errors . certain libraries that you download are not set up through NPM init . and when they publish them the root is different as a node module you will find it under npm_modules not as a static path – JonoJames Nov 09 '21 at 03:47
  • Also remember that node.js is an framework like PHP .... so you cant use node modules in PHP without converting them to standard JavaScript. Node.js uses Require and standard HTML does not ... without the require.js library or babel – JonoJames Nov 09 '21 at 03:53
  • The package works fine and is linked correctly i think because when I put some code in the public app.js file (compiled from the resource app.js file) that uses big.js like for example `console.log(Big(1.0));`, that code is processed fine. However, if i try to access Big from the views, i get the reference error, regardless of which one of the blade views I use whether it is the app.blade.php view which imports the public app.js file or the create.blade.php which extends the app.blade.php component – amjad756 Nov 09 '21 at 10:51
  • Package works fine, try to add the require file in the last of the importing list. – kshitij Nov 10 '21 at 07:14
  • still getting the same error even with require at the end of the file. – amjad756 Nov 10 '21 at 09:49
  • No error if i use the cdn instead of the npm package for some reason. Any reason why the npm package not working. what am i missing? – amjad756 Nov 10 '21 at 19:02

0 Answers0