为默认导出模块编写声明文件

编程入门 行业动态 更新时间:2024-10-28 12:24:59
本文介绍了为默认导出模块编写声明文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个名为 RiveScript 的 npm 模块,它通常(在 Javascript 中)以这种方式实例化:

I have a npm module called RiveScript that usually (in Javascript) gets instantiated that way:

var RiveScript = require('rivescript'); var rivescript = new RiveScript();

我正在尝试为模块编写声明文件,但在第一步卡住了.以下是我到目前为止所写的内容:

I'm trying to write a declaration file for the module, but am stuck at the first step. Here's what I've written so far:

declare module "rivescript" { interface RivescriptOptions { utf8?: boolean; } class RiveScript { constructor(options?: RivescriptOptions); } export default RiveScript; }

然后我想在 Typescript 中我会以这种方式使用模块(默认导入):

Then I guess in Typescript I would be using the module this way (default import):

import RiveScript from 'rivescript'; let rivescript = new RiveScript();

然而,tsc 生成了这个,这是无效的,因为它引用了一个 default() 函数:

However, tsc generates this, which is not valid as it references a default() function:

const rivescript_1 = require('rivescript'); let rivescript = new rivescript_1.default();

我做错了什么?

推荐答案

你真的很接近.您应该使用 export = 而不是使用 export default.

You're really close. Instead of using export default, you should use export =.

custom-typings/rivescript.d.ts

declare module 'rivescript' { class RiveScript { constructor() } export = RiveScript }

app.js

import RiveScript = require('rivescript'); let rivescript = new RiveScript();

有关如何编写声明文件的更多信息,您应该查看 打字稿手册.例如.他们有一个将模块作为一个类导出"的模板.

For more info on how to write declaration files, you should have a look at the Typescript Handbook. Eg. they have a template for 'exporting modules as a class.

更多推荐

为默认导出模块编写声明文件

本文发布于:2023-07-12 07:28:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1096862.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模块   声明   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!