javascriptreactjsmomentjscode-splitting

How to dynamically import moment.js in a react app (with typescript)


I'm trying to do some code splitting and moment.js is one of the targeted packages I want to isolate in a separate chunk. I'm doing it like this:

const myFn = async (currentNb) => {
   const moment = (await import('moment')).default()          
   const dateUnix: number = moment(currentNb).valueOf()
   [...]
}

But I get the following error: this expression is not callable. Type Moment has no call signatures . So I guess I should be doing something like moment.valueOf(currentNb) but I'm not really sure. Can someone put some light to this? Thanks in advance


Solution

  • So apparently my syntax was incorrect. I finally found how to solve this problem. I need to import it as follows:

    const {default: moment} = await import('moment')
    

    I found the answer in the webpack documentation:

    The reason we need default is that since webpack 4, when importing a CommonJS module, the import will no longer resolve to the value of module.exports, it will instead create an artificial namespace object for the CommonJS module.