Skip to content
Advertisement

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:

require('moment/moment.js');
require('./bootstrap');
require('bootstrap-select');

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

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

mix.setResourceRoot('laravel/public');

mix.js('resources/js/app.js', 'public/js')
     .combine([
          'resources/theme/dist/js/app.js',
          'resources/theme/dist/js/app.init.js',
          'resources/theme/dist/js/sidebarmenu.js',
          'resources/theme/dist/js/waves.js',
          'resources/theme/assets/libs/perfect-scrollbar/dist/perfect-scrollbar.jquery.min.js',    
          'resources/theme/assets/extra-libs/sparkline/sparkline.js',  
          'resources/theme/dist/js/custom.js',
          'resources/js/custom.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();
    console.log(date);
});

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?

Advertisement

Answer

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’);
moment().format();

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');
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement