首页 > 解决方案 > 将 moment.js 排除在我的 Angular 构建输出之外

问题描述

我正在开发一个 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;,但它们没有给我类型安全,而且我找不到moment.d.ts通过tsconfig "files"属性或项目tsconfig.app.json "include"属性中导入的方法。

有没有办法使这项工作?

谢谢!

标签: angulartypescriptmomentjstypescript-typings

解决方案


毕竟,我似乎找到了解决方案。

解决方案是双重的:

  1. 暂时在页面中插入一个script标签,并为适当的语言环境插入一个标签。我在服务器生成的 MVC 视图中执行此操作。index.html我用于 Angular 开发的页面中包含相同的两个标签ng serve
    在 globalmoment中提供了一个对象。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'];.
    这不会给我任何类型安全,但我可以利用importTypescript 的新语法(这里是一个很好的演示,这里是参考)来访问模块的类型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,并且仍然可以编写类型安全的代码。


推荐阅读