1

I have a module named player to re use data for alpine. its giving me Alpine Expression Error: player is not defined.

I have tried to remove defer from app.js script tag and moved it from <head> to footer but no effect. I checked in webpack output app.js, module is bundled fine.

Here is my setup.

resources/js/app.js

require('./bootstrap');

import Alpine from 'alpinejs';
import player from './player'

window.Alpine = Alpine;

Alpine.data('player', player)

Alpine.start();

and my player.js is in same folder

export default () => ({
    playing: false,
    muted: false,
    speed: 1,

    playToggle() {
        this.playing = ! this.playing
    },
    muteToggle() {
        this.muted = ! this.muted
    }
})

and in blade component I am using it on root div

<x-guest-layout>
    <div x-data="player">...</div>
</x-guest-layout>

Layout is like this

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <title>{{ config('app.name', 'Laravel') }}</title>

        <!-- Fonts -->
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap">

        <!-- Styles -->
        <link rel="stylesheet" href="{{ asset('css/app.css') }}">

        @stack('head-stack')

        <!-- Scripts -->
        <script src="{{ asset('js/app.js') }}" defer></script>
    </head>
    <body>
        <div class="font-sans text-gray-900 antialiased">
            {{ $slot }}
        </div>
    </body>
    @stack('body-stack')
</html>

Can you guys help whats I am missing here. I followed official doc of alpinejs here https://alpinejs.dev/globals/alpine-data#registering-from-a-bundle

Saqueib
  • 3,484
  • 3
  • 33
  • 56
  • import `player.js` not `player`. – Kim Hallberg Aug 08 '22 at 07:18
  • 2
    Your code looks correct. Are you sure you're loading in the script correctly in your layout? – Yinci Aug 08 '22 at 08:45
  • @Yinci script is loaded since it works when in inline `x-data="{player: {playing: false}}"` like this. Updated my question with layout code – Saqueib Aug 09 '22 at 04:13
  • 2
    Since your code looks ok and works fine (eg: https://codesandbox.io/s/alpine-js-forked-lx0jb9). It's likely some kind of loading order issue in context of php may be? – Shaunak Aug 09 '22 at 04:37
  • When you open your `js/app.js`, you are certain the player code is in there? Your layout also looks perfect, and as demonstrated by the sandbox above, the code is functional. – Yinci Aug 09 '22 at 06:12

0 Answers0