如何为导出功能的commonjs模块编写定义文件 [英] How to write a definition file for commonjs module that exports function
本文介绍了如何为导出功能的commonjs模块编写定义文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在打字稿中使用简单的commonjs模块,这是3个文件
I want to use simple commonjs module in typescript, and here are 3 files
原始lib:
//commonjs-export-function.js
module.exports = function() {
return 'func';
};
定义文件:
//commonjs-export-function.d.ts
declare function func(): string;
export = func;
使用它的打字稿程序:
//main.ts
import { func } from './commonjs-function';
console.log(func());
运行tsc时出现此错误:
When I run tsc I get this error:
tsc main.ts && node main.js
main.ts(1,22): error TS2497: Module '"/Users/aleksandar/projects/typescript-playground/commonjs-function"' resolves to a non-module entity and cannot be imported using this construct.
这里也已经回答了问题,但不适用于打字稿2.0
here is also already answered question but it doesn't work with typescript 2.0
推荐答案
我在这里的打字稿文档中找到了解决方案: http://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-function-d-ts.html
I found the solution in typescript docs here: http://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-function-d-ts.html
*~ Note that ES6 modules cannot directly export callable functions.
*~ This file should be imported using the CommonJS-style:
*~ import x = require('someLibrary');
...
export = MyFunction;
declare function MyFunction(): string;
所以mu定义文件应该是:
so mu definition file should be:
//commonjs-export-function.d.ts
declare function func(): string;
export = func;
并使用require导入:
and import with require:
//main.ts
import func = require('./commonjs-export-function');
这篇关于如何为导出功能的commonjs模块编写定义文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文