【问题标题】:using Moment with Angular library 13 causes an error将 Moment 与 Angular 库 13 一起使用会导致错误
【发布时间】:2022-01-05 15:55:32
【问题描述】:

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

vendor.js:sourcemap:106713 ERROR TypeError: (moment__WEBPACK_IMPORTED_MODULE_2___namespace_cache || (intermediate value)(intermediate value)) 不是函数。 例如,当我在浏览器中调试 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"
>     ],

【问题讨论】:

  • 尝试“目标”:“es2020”,“模块”:“es2020”,“lib”:[“es2020”,“dom”]
  • 很遗憾,它没有用
  • 你试过使用“module”:“es2015”吗?如果您已经解决了,我想知道如何解决。

标签: angular typescript upgrade


【解决方案1】:

devdocs 有解决这个问题的办法:

所以,你需要添加库tsconfig.lib.json和项目tsconfig.json

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

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

【讨论】:

  • 此解决方案有效,如果您想追踪详细信息,请查看ng-packagr 的问题:github.com/ng-packagr/ng-packagr/issues/2215。我不需要在使用 lib 的 angular 项目中触摸任何东西。我只更改了 lib 本身的 tsconfig,添加了 allowSyntheticDefaultImports: trueimport moment from 'moment' 而不是 import * as moment from 'moment'
  • 此解决方案有效。请记住,如果您尝试将 @yourpackage 拖到 node_modules 上,请清除您的 .angular 缓存文件。
【解决方案2】:

您可以尝试在您的 Angular 应用程序中禁用严格模式和模板检查,如下示例 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
  }
}

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

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

import * as moment from 'moment'; 

【讨论】:

  • 我尝试了很多东西,但没有任何效果。问题是,由于某种原因,在我的角度库中升级到版本 13 之后。未导入 lib moment.js。在角度应用程序中。它完美地工作。我没有收到任何编译错误。
【解决方案3】:

我有同样的问题,我让它工作的唯一方法是除了在 tsconfig.lib.json 上使用 allowSyntheticDefaultImports 我还必须在我的库的 package.json 的依赖项部分添加时刻(也添加这个异常到 ng-package.json 上的 allowedNonPeerDependencies)。

【讨论】:

    猜你喜欢
    • 2011-06-30
    • 1970-01-01
    • 2013-11-11
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    相关资源
    最近更新 更多