Highcharts: 使用 `import` 将 `moment.js` 作为模块加载

创建于 2018-07-23  ·  3评论  ·  资料来源: highcharts/highcharts

预期行为

当使用import作为模块加载时,Highcharts 应该能够找到moment import

实际行为

moment未保存在window ,因此 Highcharts 在尝试访问moment时失败,例如:
https://github.com/highcharts/highcharts/blob/3c8867e8ead548ada66c38f73fce74b2130dac8b/js/parts/Time.js#L370

带有重现步骤的现场演示

https://codesandbox.io/s/7yyz98kv4x

查看app/app.component.ts代码和注释

建议的解决方案

添加 API 选项,例如time.moment将为用户设置,因此可以在上面引用的代码中加载moment ,例如:

moment = options.moment || win.moment;

POC: https :

解决方法

momentwindow.moment ,这样 Highcharts 就能找到它。 例如:

import * as moment from "moment";

window.moment = moment;
Enhancement

最有用的评论

非常感谢这个提示,以下 snipit 对我来说很好用:

import { Component, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';

import * as Highcharts from 'highcharts';
import ExportingModule from 'highcharts/modules/exporting';
import * as Moment from 'moment';
import * as mTZ from 'moment-timezone';

declare global {
  interface Window {
    moment: any;
  }
}
window.moment = Moment;
mTZ();

ExportingModule(Highcharts);
Highcharts.setOptions({
  title: {
...

@Component({
...
})
export class CellPowerGraphComponent implements OnInit, OnDestroy {
...

所有3条评论

有同样的问题,但您建议的解决方法对我不起作用。
我在编译时收到错误消息:
apps/frontend/src/app/solar-data/cell-power-graph/cell-power-graph.component.ts(8,8): error TS2339: Property 'moment' does not exist on type 'Window'.

它的设置方式如下:

import { Component, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';

import * as Highcharts from 'highcharts';
import ExportingModule from 'highcharts/modules/exporting';
import * as Moment from 'moment';
import * as mTZ from 'moment-timezone';

window.moment = Moment;
mTZ();

@mfechner
该错误不会影响构建 JavaScript - 除非您配置防止在 TS 错误上构建。 我的解决方案只是一种解决方法,因此您可以通过将window强制转换为any或使用任何其他方法来抑制此错误来忽略此 TS 错误。

(window as any).moment = Moment;

或者您可以扩展Window接口并添加moment定义,这是此类错误的正确解决方案。

非常感谢这个提示,以下 snipit 对我来说很好用:

import { Component, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';

import * as Highcharts from 'highcharts';
import ExportingModule from 'highcharts/modules/exporting';
import * as Moment from 'moment';
import * as mTZ from 'moment-timezone';

declare global {
  interface Window {
    moment: any;
  }
}
window.moment = Moment;
mTZ();

ExportingModule(Highcharts);
Highcharts.setOptions({
  title: {
...

@Component({
...
})
export class CellPowerGraphComponent implements OnInit, OnDestroy {
...
此页面是否有帮助?
0 / 5 - 0 等级