Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.js and the rollup module bundler

Is there any way to make Moment.js work with rollup without having to change this import statement:

import * as moment from "moment"

I tried to use rollup inject plugin but I didn't manage to make it work.

like image 454
A. Agius Avatar asked Nov 22 '25 10:11

A. Agius


1 Answers

As explained here, since version 2.10.0, moment is written using ECMAScript 6 modules. The library should therefore be directly compatible with Rollup. Here's a solution using npm :

  • Add moment to your node_modules: npm install moment --save

To use npm modules with Rollup.js, you need to have these 2 plugins installed in your devDependencies: rollup-plugin-commonjs and rollup-plugin-node-resolve. The first one enables you to use Node's CommonJS modules as if they were ECMAScript modules (= use the import syntax to load them).

  • Import the module in your code: import moment from "moment";

You can now use moment normally, for instance:

console.log(moment().format());

I'm new to Rollup and I've still trying to figure out how things work. I've made a simple test with the solution above and it seems to work, except that the whole library gets included in the bundle — the expected tree-shaking didn't happen and I don't know why.

like image 142
Nicolas Le Thierry d'Ennequin Avatar answered Nov 24 '25 09:11

Nicolas Le Thierry d'Ennequin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!