'using Moment with Angular library 13 causes an error

When i use the moment.js (latest version) in an angular library, i am facing the following problem:

vendor.js:sourcemap:106713 ERROR TypeError: (moment__WEBPACK_IMPORTED_MODULE_2___namespace_cache || (intermediate value)(intermediate value)) is not a function. When i debug in the browser the moment().year() for example it works.

Can anyone have an idea, what is the reason for this error? maybe the EcmaScript version.

I will appreciate for any help.

> "compilerOptions": {
>     "declaration": false,
>     "downlevelIteration": true,
>     "experimentalDecorators": true,
>     "lib": [ "es6", "dom" ],
>     "mapRoot": "./",
>     "module": "esnext",
>     "skipLibCheck": true,
>     "moduleResolution": "node",
>     "outDir": "../dist/out-tsc",
>     "sourceMap": true,
>     "target": "ES2015",
>     "typeRoots": [
>       "../node_modules/@types"
>     ],


Solution 1:[1]

The devdocs has a solution to this problem:

So, you need add in library tsconfig.lib.json and in project tsconfig.json:

"compilerOptions": {
    ...
    "allowSyntheticDefaultImports": true,
    ...
}

And then use the syntax import moment from 'moment';

Solution 2:[2]

You could try to disable strict mode and template check in your angular application as below sample tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": false,
    "noImplicitOverride": false,
    "noPropertyAccessFromIndexSignature": false,
    "noImplicitReturns": false,
    "noFallthroughCasesInSwitch": false,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2017",
    "module": "es2020",
    "skipDefaultLibCheck": true,
    "skipLibCheck": true,
    "lib": [
      "es2020",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": false,
    "strictInputAccessModifiers": false,
    "strictTemplates": false
  }
}

For more information refer how to turn off strict to true in angular application

In addition when you are using moment in your application try to import as follow:

import * as moment from 'moment'; 

Solution 3:[3]

I had the same problem and the only way I got it to work was besides using allowSyntheticDefaultImports on tsconfig.lib.json I also had to add moment to the dependencies section on the package.json of my library (also adding this exception to allowedNonPeerDependencies on ng-package.json).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Denis
Solution 2 Andongwisye Mwamengo
Solution 3 Marcello