datetimepicker for Laravel Vite Not Working

587 Views Asked by At

I have this on my package.json file

"moment": "^2.24.0",
"eonasdan-bootstrap-datetimepicker": "^4.17.47",

On my resolve-alias on my vite.config.js:

'moment': path.resolve(__dirname, 'node_modules/moment'),
'eonasdan-bootstrap-datetimepicker': path.resolve(__dirname, 'node_modules/eonasdan-bootstrap-datetimepicker'),

On my app.js file:

import moment from 'moment';
window.moment = moment;
import eonasdan_datimepicker from 'eonasdan-bootstrap-datetimepicker';
window.datetimepicker = eonasdan_datimepicker;

On my blade file:

@vite('resources/sass/app.scss')
@vite('resources/js/app.js')

My initialization:

$('#element').datetimepicker({
    sideBySide: true,
    ignoreReadonly: true,
    icons: {
        up: "fa fa-caret-up fa-3x",
        down: "fa fa-caret-down fa-3x",
        next: 'fa fa-angle-right',
        previous: 'fa fa-angle-left'
    }
});

I got an error on the developer console that says

Uncaught TypeError: moment2.locale is not a function at node_modules/eonasdan-bootstrap-datetimepicker/src/js/bootstrap-datetimepicker.js

Any thoughts on why can't i use the eonasdan-bootstrap-datetimepicker package on laravel-vite. I can use this package seemlessly on laravel-webpack on my past projects. Now I am trying to make it work on laravel-vite but got stuck on this.

1

There are 1 best solutions below

1
On

The error you are getting is because Vite is using a different version of Moment than the one that eonasdan-bootstrap-datetimepicker is expecting. You can fix this by importing the Moment package from npm instead of from node_modules.

In your vite.config.js file, change the following line:

'moment': path.resolve(__dirname, 'node_modules/moment'),

to this:

'moment': 'moment',

This will tell Vite to use the Moment package from npm.

You should also remove the following line from your app.js file:

window.moment = moment;

This line is no longer necessary since Vite will automatically inject the Moment package into the global window object.

Once you have made these changes, you should be able to use eonasdan-bootstrap-datetimepicker without any errors.

Here is the updated code for your vite.config.js and app.js files:

vite.config.js

import { defineConfig } from 'vite';

export default defineConfig({
  resolve-alias: {
    'moment': 'moment',
  },
});

app.js

import moment from 'moment';

$('#element').datetimepicker({
  sideBySide: true,
  ignoreReadonly: true,
  icons: {
    up: "fa fa-caret-up fa-3x",
    down: "fa fa-caret-down fa-3x",
    next: 'fa fa-angle-right',
    previous: 'fa fa-angle-left'
  }
});

I hope this helps!