How to include moment.js with webpack? SOLVED

I’m trying to add Tempus Dominus datetimepicker into Sage 9 which requires moment.js as a dependency.

I have tried various combinations of imports into webpack and I can get it to compile properly but the page doesn’t load properly and the browser console logs: Uncaught Error: Tempus Dominus Bootstrap4's requires moment.js. Moment.js must be included before Tempus Dominus Bootstrap4's JavaScript.

I have tried various ordering in main.js and also tried to namespace and library.add(moment) but I am going nowhere.

Does anyone know where I am going wrong?

Thanks!

Hey @Liam,

After looking around a bit, the only way I found to get this working was to shim the moment global in the webpack config.

In webpack.config.js, add moment to the array passed to ProvidePlugin:

new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  'window.jQuery': 'jquery',
  Popper: 'popper.js/dist/umd/popper.js',
  moment: 'moment',
}),

Once you’ve done that, you don’t need to import moment in any of your other JS files; it will be available as needed.

Example home.js:

import "tempusdominus-bootstrap-4";

export default {
  init() {
    // JavaScript to be fired on the home page
    $("#datetimepicker1").datetimepicker();
  },
  finalize() {
    // JavaScript to be fired on the home page, after the init JS
  },
};

Someone else may know of a better way.

3 Likes

Thank you heaps @mmirus. This has got me out of trouble!

1 Like