在Typescript中使用CommonJS模块中的类 [英] Use class from CommonJS module in Typescript
问题描述
我有一个npm软件包,其文件类似于以下文件:
I have an npm package with a file similar to this:
'use strict'
module.exports = class TModel {
constructor (app) {
this.app = app
}
static schema () {
}
}
我想在像这样的Typescript文件中使用:
Which I want to use in a Typescript file like so:
import Model from 't-model';
export class Book extends Model {
static schema() : any {
return {
title: {
type: 'string'
}
}
}
}
但这不是工作。 PHPStorm给出错误:
But this doesn't work. PHPStorm gives the error:
无法解析文件
Cannot resolve file
然后使用tsc进行编译会出现以下错误:
And compiling with tsc gives me the error:
错误TS2307:找不到模块 t-model
error TS2307: Cannot find module 't-model'
如果使用't-model / index'
而不是 -model'
PHPStorm停止给我一个错误,但tsc仍然给出相同的错误。
If use 't-model/index'
instead of 't-model'
PHPStorm stops giving me an error but tsc still gives the same error.
我正在尝试统一我将为后端API和使用Typescript的前端。有办法吗?
I am trying to unify packages I would make for the backend API and the frontend, which uses Typescript. Is there a way to do this?
推荐答案
有一个npm软件包,其文件与此类似:
have an npm package with a file similar to this:
如果此文件是打字稿
而不是:
If this file is typescript
instead of:
module.exports = class TModel {
执行 export class TModel
,并让TypeScript生成 module.exports
(使用<$编译c $ c> module:commonjs )。这样TypeScript可以理解导出内容
Do export class TModel
and let TypeScript generate the module.exports
(compile with module: commonjs
). This way TypeScript understands the exports
有关此内容的更多信息: https://basarat.gitbooks.io/typescript/content/docs/project/modules.html
More on this : https://basarat.gitbooks.io/typescript/content/docs/project/modules.html
您需要声明它:
declare module 't-model' {
class TModel // .....
export = TModel;
}
有关此内容的更多信息: https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html
More on this : https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html
这篇关于在Typescript中使用CommonJS模块中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!