How to use a separte js file in Laravel Blade Html?

How to use a js file outside Laravel Blade html?

Besides my layouts file, I have a single file welcome.blade.php for the html and it requires a fair amount of scripts. To improve neatness, I wanted to move the <scripts> from the bottom of welcome.blade.php into a separated .js file.

See below for current code, mainly a test to get things working.

welcome.blade.php

@extends('layouts')

@section('content')
  <div>
    Body Content
  </div>
@endsection

// Script added to the bottom of welcome.blade
// How to move into a separated file, like in resources/js/welcome.js 
// <script src='/js/welcome.js'></script> doesn't work
<script>
  alert('js works');
</script>

Even when I create a new welcome.js script inside the resources/js folder, linking via src or assets doesn’t work.

I don’t want to put it in the app.js (default laravel install folder structure), because then it’ll load in for EVERY page, instead of just welcome.js.

I’ve tried using stack, but the file doesn’t exist when using asset. However, it does work when writing the script itself into the push block. But then that’s not using a separate .js file anyway…

layouts.blade.php

<body>
...
@stack('scripts')
</body>
</html>

welcome.blade.php

...
@push('scripts')
  // Works when directly writing the script here
  // Trying to use `<script src="{{ asset('js/welcome.js' }}"></script>` fails
  // No js/welcome.js found. 
  <script>
    alert('js works');
  </script>
@endpush

How can I use a separate .js file inside a Laravel Blade HTML Template?

Edit

Did I actually need to make the welcome.js script public in webpack mix? It seems to work now after adding the additional .js line.

See answer.

Versions: Laravel 8