CaptainJackas's avatar

Laravel + Vite -> ReferenceError: moment is not defined

Hi all, I am new to Vite and I'm getting pretty frustated trying to add moment.js. I tried numerous suggestions found online but with no result so far, as I'm still receiving the ReferenceError: moment is not defined when I perform a console.log(moment); in my blade. I ran npm install moment@latest --save-dev to install moment.js and npm run build to build the js file added in my blade using @vite(['resources/js/app.js']). Can anyone please help me out here? My setup in as follows:

vite.config.js

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/sass/app.scss',
                'resources/js/app.js'
            ],
            refresh: true,
        })
    ],
});

bootstrap.js

import 'bootstrap';

import axios from 'axios';
window.axios = axios;

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

import $ from 'jquery';
window.jQuery = window.$ = $;

app.js

import './bootstrap';

import 'owl.carousel';

import 'jquery-ui/dist/jquery-ui';

import DataTable from 'datatables.net-bs5';
DataTable(window, window.$);

import moment from 'moment';
window.moment = moment();

blade.php

<script type="module">
		$(document).ready(function () {
                console.log(moment);	
        });							
</script>
0 likes
6 replies
CaptainJackas's avatar

@martinbean The code I added here is only a small portion. I use jQuery in there so that would require me to use type="module" right? Does it in either way influence the error I'm getting for moment.js?

martinbean's avatar

@CaptainJackas It’s a bit difficult to help with specific problems if you’re not showing the actual code.

Why are you doing document.ready stuff in your Blade template in the first place? Why not put your code in your app.js file, where it’s meant to be?

// resources/js/app.js
import moment from 'moment';

// Do whatever you need to do with moment here...
CaptainJackas's avatar

@martinbean The problem I'm having is already with the first statement console.log(moment);, so independent from the rest of the code. Even if I remove all javascript except this statement, the error remains. I got quite some page specific js so I would rather keep it that way instead of using only app.js. It is also feels like a more of a workaround because adding moment to window should allow for it to be used outside of app.js right?

CaptainJackas's avatar
CaptainJackas
OP
Best Answer
Level 1

So apparently the line DataTable(window, window.$); in the app.js file caused the following error: Cannot set property window of #<Window> which has only a getter, which prevent moment to be imported properly. Apparently this line was redundant so after deleting it momentjs was imported properly.

1 like

Please or to participate in this conversation.