Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

inda's avatar
Level 1

Load function from app.js + vite

How can I call a function from app.js in blade template. app.js built with vit.

example app.js:

function User(name) {
    this.name = name;
  
    this.sayHi = function() {
      alert( "My name is: " + this.name );
    };
}

in blade template call:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="h-full">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Admin</title>
    @vite('resources/css/app.css')
    @vite('resources/js/app.js')
</head>
<body class="h-full">

<script>
    let john = new User("John");
    john.sayHi(); 
</script>  

</body>
</html>

But this code doesn't work. What to do, how to call a function from app.js?

0 likes
4 replies
OussamaMater's avatar

You need to put your helper in the global scope, so something like this

window.userHelper= function(name) {
      alert( "My name is: " + name );
}

Edit: you can pass an array to the vite helper, instead of calling it twice

@vite(['resources/css/app.css', 'resources/js/app.js'])
2 likes
thinkverse's avatar

You need to add the User function to the global object and then make sure your inline script is a JavaScript module.

function User(name) {
    this.name = name;

    this.sayHi = function() {
      alert( "My name is: " + this.name );
    };
}

window.User = User;
<script type="module">
    let john = new User("John");
    john.sayHi();
</script>
Npdlink352's avatar

I always use this at the top of my blades if I am going to use JS scripts in it.

// Example using BusyLoad:

// < s cript src="{{url('/')}}/busy-load/app.min.js"></ script>

// Than later on do something like.

// < s cript>

// $.busyLoadFull("show", { text: "LOADING RECORDS...",fontSize: "2rem"});

// </ s cript>

Please or to participate in this conversation.