Encountering problems while compiling Laravel, Webpack, and Sparkline

Having trouble integrating the Sparkline JavaScript package into my Laravel 5.8 project using Laravel Mix. The Sparkline isn't displaying, and I'm encountering a browser console error.

Error: Uncaught ReferenceError: sparkline is not defined.

It seems like I'm not calling it correctly.

These are the steps I've followed:

1. Installed the sparkline package using npm

npm install @fnando/sparkline --save-dev

Verified that the package is installed in node_modules (node_modules/@fnando/sparkline)

2. Added an entry to webpack.mix.js file:

mix.js([
    'resources/js/app.js',
    'node_modules/@fnando/sparkline'
    ],'public/js');

3. Imported the package in my ./resources/js/app.js:

import sparkline from "@fnando/sparkline"

4. Ran webpack with npm run dev to generate assets: ./public/js/app.js.

5. Referenced these assets in my master layout blade as shown below:

[.. snip ..]
        <script src="{{ asset('js/resources.js') }}"></script>
        <script src="{{ asset('js/semantic.js') }}"></script>
        <script src="{{ asset('js/app.js') }}"></script>

        <script>
        $('.ui.dropdown').dropdown();
        $('.ui.sticky').sticky({
            offset: 50,
            context: '#content'
        });

        @stack('inline_scripts')
        </script>
    </body>
</html>

6. Attempted to render the sparkline in my blade template as follows:

@extends('layouts.master')

@section('content')

<div class="ui secondary segment">
    <h4>Sparklines!</h4>
    <div class="ui two column centered grid">
        <div class="column">
            <svg class="sparkline" width="100" height="30" stroke-width="3"></svg>
        </div>
    </div>

</div>

@push('inline_scripts')
sparkline.sparkline(document.querySelector(".sparkline"), [1, 5, 2, 4, 8, 3, 7]);
@endpush

@endsection

Answer №1

Get the jQuery Sparklines plugin by installing it as an NPM package.

npm install @fnando/sparkline

Adjust your Webpack configuration file accordingly.

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

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css')
    .copy('node_modules/@fnando/sparkline/dist/sparkline.js', 'public/js');

Compile all your assets together.

npm run production

The plugin will be compiled into /public/js/app.js for use in your Blade template; make sure to include it at the top of the Blade file within the header section.

    <script src="{{ mix('js/app.js') }}"></script>
    <script src="{{ mix('js/sparkline.js') }}"></script>
</head>
<body>

<svg class="sparkline" width="100" height="300" stroke-width="3"></svg>
<script>
    sparkline.sparkline(document.querySelector(".sparkline"), [1, 5, 2, 4, 8, 3, 7]);
</script>
</body>
</html>

Answer №2

Thanks to the assistance of the project author, I have discovered the following steps:

To begin, install the sparkline package using npm:

    npm install @fnando/sparkline --save-dev

Next, include an import in my ./resources/js/app.js file and link it with the window object:

    import sparkline from "@fnando/sparkline"
    window.sparkline = sparkline

Afterwards, run webpack using npm run [dev|production] to generate assets like ./public/js/app.js.

I then referenced these assets in my master layout blade as shown below:

[.. snip ..]
        <script src="{{ asset('js/resources.js') }}"></script>
        <script src="{{ asset('js/app.js') }}"></script>

        <script>
            @stack('inline_scripts')
        </script>
    </body>
</html>

Lastly, render the sparkline in my blade template like this:

    @extends('layouts.master')

    @section('content')

    <div>
        <h4>Sparklines!</h4>
        <div class="column">
            <svg class="sparkline" width="100" height="30" stroke-width="3"></svg>
        </div>
    </div>

    @push('inline_scripts')
        sparkline.sparkline(document.querySelector(".sparkline"), [1, 5, 2, 4, 8, 3, 7]);
    @endpush

    @endsection

No modifications are needed in webpack.mix.js; the changes made in app.js involve importing and utilizing the package. This approach differs significantly from the previous solution, as it bundles the JavaScript package into the compiled app.js file, offering a potential advantage over simply serving the distributed .js locally and loading it via a <script src=""> tag.

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

Persistent Express session issue when redirecting in Node.js

My current setup involves using node.js and pgAdmin to establish a server with sessions, cookies, and all necessary functionalities. However, I encountered an error stating "TypeError: Cannot read property 'username' of undefined" when attempting ...

Can the Three.js Orbit Controls be customized to modify their appearance?

While I appreciate the orbit controls that come with Three.js, I am wondering if there is a way to customize them to follow the path of an ellipse (or technically an ellipsoid) instead of a circle. My main goal is to move the camera in an ellipse using th ...

The initial value set for the innerHTML property of a div element

I have a requirement in my application where I need to confirm if the container div is empty before adding specific text elements to it. The innerHTML of this div is frequently created and removed within the app, so it's crucial to validate its emptin ...

Is it possible to include additional information when initiating a WebSocket connection?

Is there a method to transmit a distinct identifier to the server upon initiating a WebSocket connection? One possible approach could involve sending a handshake message post-connection establishment. However, it would be more convenient if it were feasib ...

Beginner coding exercises to master JavaScript

With a proficiency in CSS, HTML, and some knowledge of Jquery and PHP, I aspire to become a Front End Web Developer. However, my lack of understanding in Javascript is holding me back. I acquired my current skillset by rapidly learning over 9 months while ...

"I encountered a CORS error with Framework7's $$.ajax, yet interestingly enough,

Struggling for hours with CORS error while using Framework $$.ajax, I finally decided to seek assistance from the community. I am experimenting with PhoneGap and Framework7. Trying to access an API on my .local domain is resulting in a CORS error "Cross-O ...

Is there a way to combine the elements of one array with their counterparts in multiple other arrays using JavaScript or Angular?

I am trying to combine the elements of multiple arrays in a specific order, similar to the question found at [How can I add each element of one array to another one's corresponding element using a ParallelStream?. However, my approach involves using ja ...

What is the best way to pass a dynamically generated component as the ng-content for another dynamically generated component?

Need help with creating a modal for our library using viewRef.createComponent. I want to generate Component A and embed Component B inside it, utilizing <ng-content> to fetch content from Component B. Component A serves as the modal template, while ...

Can the echoing of NPM commands be hidden or silenced during execution?

Currently, I have a bash script that initiates a server and executes some functional tests. To streamline the process, I am running the server in the background using the npm commands start:nolog and test:functional. Everything is functioning correctly, b ...

Detecting errors in asynchronous functions within other asynchronous functions

I'm attempting to capture errors in nested asynchronous functions to perform a rollback if an error occurs. Initially, I have a try-catch block where I call a function that then calls another function. The final function should throw an error, and I ...

Placing JavaScript at the bottom of the page, sourced from a Partial Page

I'm trying to display JavaScript code from a Razor Partial Page at the bottom of a (layout) Page. In a similar discussion on Stack Overflow about Including JavaScript at bottom of page, from Partial Views, it was suggested by user Becuzz that using a ...

Can you explain the compatibility between comet and PHP?

As I utilize Comet iframe, I simply send script tags from the backend PHP file to the frontend where JavaScript displays them. I would appreciate it if someone could provide a concise explanation of how the comet server fits into the equation and how comm ...

Determine the central x and y coordinates of elements depending on the specified screen dimensions

Is it possible to determine the center position of an element at a specific screen size using jQuery? I am looking to calculate the center position of an element based on provided height and width dimensions. For instance, if I provide the screen size (1 ...

Come together in a Statement by utilizing the Query builder and incorporating multiple where clauses

I am facing an issue with my Query builder statement. I want to add an additional condition to the query but I am struggling to do so. The current query is functioning correctly; $content = DB::table('subscribed_services as a') ->join(' ...

Transform a string into JSON format containing numerous objects

Currently, I'm utilizing angular formly to create various forms. These forms are being fetched from my database as multiple JSON objects. However, in JavaScript, I am seeking guidance on how to convert a string like the one below into an array of obje ...

Leverage the power of lodash or es6 by creating a custom function that accepts an object containing deeply nested properties and outputs a new object containing only specific properties

I have a complex object with unnecessary properties and deeply nested values that I need to filter. My objective is to transform this initial object into a new object containing only the specific fields I require. Here's an illustration of the large ...

A step-by-step guide on utilizing links for downloading PDF files in Vue/Nuxt

Having some trouble opening a PDF tab in my Vue application with NUXT and Vuetify... any suggestions? I attempted to use: <a href="../static/docs/filename.pdf" target="_blank">Download PDF</a> I also tried using <nuxt-link> but it didn ...

Error: The name property is not defined and cannot be read in the Constructor.render function

Having trouble building a contact form and encountering an error when trying to access the values. I've checked for bugs in the console multiple times, but it seems like something is missing. Can anyone provide assistance? var fieldValues = { ...

Exploring HTML5 video playback in AngularJS

When I use this code: <video id="video" class="video-js vjs-default-skin" controls width="640" height="264"> <source src="http://localhost:3000/files/public/photos/Let-her-go.mp4" type='video/mp4' /> <p class="v ...

the button function is unresponsive

Can someone please help me troubleshoot my jQuery code? Everything seems fine, but the generate button is not working when clicked! PS: I've searched extensively for a solution to this problem but haven't been able to find one. I've also at ...