将 Moment 与 Angular 库 13 一起使用会导致错误

Eva*_* ps 5 upgrade typescript angular

当我在角度库中使用 moment.js (最新版本)时,我面临以下问题:

vendor.js:sourcemap:106713 错误 TypeError: (moment__WEBPACK_IMPORTED_MODULE_2___namespace_cache || (中间值)(中间值)) 不是函数。例如,当我在浏览器中调试 moment().year() 时,它可以工作。

任何人都可以知道这个错误的原因是什么?也许是 EcmaScript 版本。

我将不胜感激任何帮助。

> "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"
>     ],
Run Code Online (Sandbox Code Playgroud)

小智 12

开发文档对此问题有一个解决方案:

tsconfig.lib.json因此,您需要在库和项目中添加tsconfig.json

"compilerOptions": {
    ...
    "allowSyntheticDefaultImports": true,
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后使用语法 import moment from 'moment';

  • 这个解决方案有效。如果您尝试将 @yourpackage 拖到 node_modules 上,请记住清除您的 .angular 缓存文件。 (3认同)

小智 0

您可以尝试在角度应用程序中禁用严格模式和模板检查,如下示例 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
  }
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅如何在角度应用程序中将严格关闭为真实

此外,当您在应用程序中使用 moment 时,请尝试按以下方式导入:

import * as moment from 'moment'; 
Run Code Online (Sandbox Code Playgroud)