【问题标题】:Keeping moment.js out of my Angular build output将 moment.js 排除在我的 Angular 构建输出之外
【发布时间】:2021-03-07 05:00:37
【问题描述】:

我正在开发一个 Angular Spa(使用 Angular CLI),我希望将 moment.js 作为外部脚本包含在页面中:

    <script src="/lib/moment.min.js"></script>

这是因为我只想将相关语言环境的加载移动到服务器端,并且将 moment.js 排除在构建之外是第一步。

因此,我需要使用此导入机制使构建的其余部分正常工作,理想情况下保持 Moment.js 类型的工作正常。比如:

declare const moment: moment.MomentType;
// or something like
interface Window {
  moment: moment.MomentType
}

这种语法(或我能想到的任何变体)让我遇到Cannot find namespace 'moment' 的错误。

我已经尝试删除周围的每个 import { moment } from 'moment';,我尝试了 declare const moment: any; 的变体,但它们没有给我类型安全性,而且我找不到通过 @987654328 导入 moment.d.ts 的方法@"files" 属性或项目的tsconfig.app.json "include" 属性中。

有没有办法让它工作?

谢谢!

【问题讨论】:

    标签: angular typescript momentjs typescript-typings


    【解决方案1】:

    你可以像这样为moment js创建一个单独的构建文件

    angular.json

    "scripts": [
      {
        "inject": true,
        "bundleName": "moment-build",
        "input": "node_modules/moment/min/moment.min.js"
      }
    ]
    

    inject :true 这在index.html 中为moment-build.js 添加一个脚本元素

    作为示例,此构建通过直接在主组件中导入时刻来构建

    这是我创建单独的构建文件moment-build.js时的构建结果

    【讨论】:

    • 感谢@malbarmavi 的输入。但是,这并没有解释如何在我的 TypeScript 文件中使用 moment:我可以将它作为 window['moment'] 或类似的“hacks”来访问,但是我如何告诉 TypeScript/Angular window.moment 是主要时刻对象?
    • 作为全球可用的时刻 import { Moment } from 'moment'; declare const moment: Moment; 然后您可以访问它
    【解决方案2】:

    看来我终于找到了解决办法。

    解决方案有两个:

    1. 暂时在页面中插入一个script 标记,并为适当的语言环境插入一个标记。我在服务器生成的 MVC 视图中执行此操作。 我使用 ng serve 进行 Angular 开发的 index.html 页面中包含相同的两个标签。
      这提供了一个moment 对象在全局window内。
        <script src="/assets/lib/moment/moment.min.js"></script>
        <script src="/assets/lib/moment/locale/it.js"></script>
    
    1. 在 Angular 开发模式下,我删除了每一个 import moment from 'moment';import * as moment from 'moment'; 或其变体。
      相反,我使用本地 const moment = window['moment'];
      这不会给我任何类型安全性,但是我可以利用 Typescript 的新 import 语法(here 进行漂亮的演示,here 供参考)来访问 type moment模块:
    // just importing the module for the type
    // will not add the module to the build output
    export const moment: typeof import('moment') = window['moment'];
    type Moment = import('moment').Moment;
    type LongDateFormatSpec = import('moment').LongDateFormatSpec;
    type DurationInputObject = import('moment').DurationInputObject;
    type Locale = import('moment').Locale;
    

    而且,瞧,我们刚刚从构建中削减了大约 300 KB,并且仍然可以编写类型安全的代码。

    【讨论】:

      猜你喜欢
      • 2017-04-26
      • 1970-01-01
      • 2017-03-10
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      • 2019-12-20
      • 1970-01-01
      相关资源
      最近更新 更多