来自第三方声明模块的打字稿导入功能

时间:2019-11-25 07:44:08

标签: angular typescript d3.js

我已经跑过npm install --save-dev @types/d3-box

如何将其导入我的angular 7项目?

我已经创建了一个文件 custom-d3.ts ,如下所示:

export * from 'd3-axis';
export * from 'd3-brush';
export * from 'd3-chord';
export * from 'd3-collection';
export * from 'd3-color';
export * from 'd3-contour';
export * from 'd3-dispatch';
export * from 'd3-drag';
export * from 'd3-dsv';
export * from 'd3-ease';
export * from 'd3-fetch';
export * from 'd3-force';
export * from 'd3-format';
export * from 'd3-geo';
export * from 'd3-hierarchy';
export * from 'd3-interpolate';
export * from 'd3-path';
export * from 'd3-polygon';
export * from 'd3-quadtree';
export * from 'd3-random';
export * from 'd3-scale';
export * from 'd3-scale-chromatic';
export * from 'd3-selection';
export * from 'd3-shape';
export * from 'd3-time';
export * from 'd3-time-format';
export * from 'd3-timer';
export * from 'd3-transition';
export * from 'd3-voronoi';
export * from 'd3-zoom';
export * from 'd3-box';

在我的组件中,我将导入custom-d3,因为d3包含d3框。 import * as d3 from '../custom-d3';

在我的代码中,我想像下面这样调用d3.box():

this.boxPlot = d3.box()
   .whiskers(this.iqr(1.5))
   .height(this.graphHeight)
   .showLabels(this.labels);

这是我得到的错误:

  ERROR in src/app/components/d3/group-graph/box-graph.ts(115,27): error TS2339: Property 'box' does not exist on type 'typeof import("custom-d3")'.

谢谢

2 个答案:

答案 0 :(得分:0)

我相信创建一个shared module是您的案例的正确用法。

首先,您需要创建一个新模块shared.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
//Import everything first
import * as d3Axis from 'd3-axis';
import * as d3Brush from 'd3-brush';
import * as d3Chord' from 'd3-chord';
// .. and so on

@NgModule({
declarations: [
    //declare component here if you want to share it with all other components.
  ],
  imports: [
    CommonModule,
    d3Axis,
    d3Brush,
    d3Chord
  ],
  exports: [
    d3Axis,
    d3Brush,
    d3Chord
  ]
})

export class SharedModule { }

然后,在要使用此模块的任何其他模块中,只需要将其导入。

答案 1 :(得分:0)

感谢Giacomo Debidda https://www.giacomodebidda.com/how-to-import-d3-plugins-with-webpack/

import * as d3Base from 'd3';
import * as box from 'd3-box';

// attach all d3 plugins to the d3 library
const d3 = Object.assign(d3Base, { box });
  .whiskers(this.iqr(1.5))
  .height(this.graphHeight);

然后当我使用它时:

this.boxPlot = (d3 as any).box()