angular - 将 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"
属性中导入的方法。
有没有办法使这项工作?
谢谢!
解决方案
毕竟,我似乎找到了解决方案。
解决方案是双重的:
- 暂时在页面中插入一个
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>
- 在 Angular 开发模式下,我删除了它的每一个
import moment from 'moment';
和import * as moment from 'moment';
/或变体。
相反,我使用本地const moment = window['moment'];
.
这不会给我任何类型安全,但我可以利用import
Typescript 的新语法(这里是一个很好的演示,这里是参考)来访问模块的类型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,并且仍然可以编写类型安全的代码。
推荐阅读
- c# - 无法在 UDP 端口上捕获消息
- group-by - 如何同时加入、求和和分组
- sql - 为什么我无法运行 SQL Server 2019 setup.exe 文件?
- amazon-web-services - 403 禁止在 API 网关上使用自定义域的附加域
- python - 如果字典在 Python 中为空,则刷新 api 查询
- python - git post-receive 挂钩未触发 Jenkins 作业(机器 1:本地,机器 2:远程)
- flutter - 转换流
- > 到地图
> - python - 如何按另一个列值对重复的索引(我仍然想要按排序顺序)进行排序?
- javascript - Vanilla Javascript如何检查点击的元素是否是最后一项
- unix - 如何解决NF的排列