Skip to content

Moment js undefined Laravel

I’m trying to use moment.js in my laravel project, not using vue, but still importing the package via npm.

My app.js file:


in my webpack.pix.js file looks like this:

const mix = require('laravel-mix');    


mix.js('resources/js/app.js', 'public/js')
     ], 'public/js/nice-admin.js')
     .copyDirectory('resources/theme/assets/images/', 'public/assets/images')
     .copyDirectory('resources/theme/dist/css/icons/material-design-iconic-font/fonts', 'public/fonts')
     .copy('node_modules/bootstrap-daterangepicker/daterangepicker.css', 'public/css/daterangepicker.css')
     .copy('node_modules/bootstrap-select/dist/css/bootstrap-select.min.css', 'public/css/bootstrap-select.min.css')
     .sass('resources/sass/app.scss', 'public/css', {
           implementation: require('node-sass')
}).options({processCssUrls: false})

And then in my custom.js file I’ve just got this:

$(function() {
    "use strict";

    let date = moment().format();

I’m getting the following error:

app.js:13202 Uncaught ReferenceError: moment is not defined
    at HTMLDocument.<anonymous> (nice-admin.js:2144)
    at mightThrow (app.js:12909)
    at process (app.js:12977)

I’ve verified that moment is in my compiled app.js file. So why can’t my custom.js file see it, and what do I need to do to fix it?


You’re currently not assigning moment to anything. As per the docs, you should assign it to a variable to be used:

var moment = require(‘moment’);

However, this will not work if you want to use it outside the scope of your app.js file. One way to do this would be to add it to the window object:

window.moment = require('moment');