1

我们在一个反应​​项目中使用了一个名为Grapnel的客户端路由库。该库没有可用的定义文件,因此我编写了自己的定义文件,该文件正在工作,但我必须将其创建为全局模块并通过脚本标记以老式方式加载脚本。这不是最优的,因为项目中的所有其他 javascript 都由 webpack 捆绑。

Grapnel 通过 npm 安装;我希望能够在 webpack 中捆绑 Grapnel,并且对我们应该将定义编写为全局的场景感到好奇。Grapnel 是用 ES5 语法编写的:

!(function(root) {

    function Grapnel(opts) {
    ....
}).call({}, ('object' === typeof window) ? window : this);

因此需要实例化如下

new Grapnel({options});

我是否可以编写 .d.ts 以便我可以使用 ES6 模块导入语句?还是我需要将 Grapnel 称为全局变量?如果我必须使用全局定义,这是否会排除在 webpack 中的捆绑?

这是我的工作(全球)版本:

// Type definitions for grapnel
// Project: https://github.com/baseprime/grapnel
// Definitions by: Trevor Kilvington <http://trevorgk.js.org>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
type GrapnelEvent = "navigate" | "match" | "hashchange";

interface GrapnelOptions {
  pushState?: boolean,
  root?: string,
  hashBang?: boolean
}

interface Routes {
  [route: string]: () => void;
}

declare class Grapnel  {
  constructor(init?: GrapnelOptions)
  get(route:string|RegExp)
  navigate(route:string)
  on(eventName:GrapnelEvent, callback:() => any)
  once(eventName:GrapnelEvent, callback:() => any)
  trigger(eventName:GrapnelEvent, ...eventArgs: any[] )
  context(routeContext:string, middleware: any): () => any
  path(newPath: string)
  path(clear: boolean)
  listen(routes: Routes)
}

declare module "grapnel" {
  export = Grapnel;
}

感谢您提供的任何建议。我是编写 .d.ts 的新手,但熟悉打字稿和使用打字。

4

0 回答 0