ES6 类的 TypeScript 声明不适用于 CommonJS

问题描述

我在 TypeScript 中有一个项目,它使用 Rollup 构建 ESM 和 Commonjs 包。项目认导出一个 ES6 类。

两个包都按预期工作,可以使用 importrequire() 导入。

// Both of these work
import MyProject from 'my-project'
const MyProject = require('my-project')

但是,在使用 Commonjs 时,TypeScript 似乎认为我需要像这样附加 .default

// Types get picked up,but this is obvIoUsly wrong.
const MyProject = require('my-project').default

我的问题是,我怎样才能生成我的 TypeScript 声明以同时使用 ESM 和 Commonjs 包?

生成的声明:

import { CanvasTextBlockOptions } from "./types";
import type { Canvas as NodeCanvas,CanvasRenderingContext2D as NodeCanvasRenderingContext2D } from "canvas";
declare class CanvasTextBlock {
    canvas: HTMLCanvasElement | NodeCanvas;
    context: CanvasRenderingContext2D | NodeCanvasRenderingContext2D;
    x: number;
    y: number;
    width: number;
    height: number;
    options: required<CanvasTextBlockOptions>;
    constructor(canvas: any,x: number,y: number,width: number,height: number,options?: CanvasTextBlockOptions);
    
    getTextBlockMaxWidth: () => number;    
    getoptions: () => required<CanvasTextBlockOptions>;
    getMaxLineCount: () => number;
    setBackgroundColor: () => void;
    setTextBlock: (text: string) => void;
    getLinesFromText: (text: string) => string[];
}
export default CanvasTextBlock;

我的tsconfig.json

{
  "compilerOptions": {
    "target": "es5","module": "ESNext","strict": true,"moduleResolution": "node","strictnullchecks": true,"esModuleInterop": true,"allowSyntheticDefaultImports": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true,"declaration": true,"declarationDir": "dist"
  },"include": ["src"],}

我注意到 TypeScript 文档中的 Module: Class 声明,这似乎是我需要的。但我希望自动生成这个文件

这个项目的源代码也可以在here找到。

我希望得到任何反馈,谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...