为许多导入模式和智能感知编写打字稿

问题描述

我正在尝试将一些 javascript 模块更新为打字稿,但在保持兼容性方面遇到问题。我在 javascript 中有一些使用 commonjs 模式 const fn = require('mod'); 的旧项目,它们仍然依赖于这个模块。我试过按照打字稿指南处理这么多类型的导入:

https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html#handling-many-consuming-import

// src/mod.ts
type FnResult = Promise<void>;
function fn(): FnResult {
    return Promise.resolve();
}

fn.fn = fn;
fn.default = fn;
module.exports = fn;

这在为较旧的 javascript 项目和大多数较新的项目进行编译时非常有用。 tsc 构建以下内容

// lib/mod.js
"use strict";
function fn() {
    return Promise.resolve();
}
fn.fn = fn;
fn.default = fn;
module.exports = fn;

// lib/mod.d.ts
declare type FnResult = Promise<void>;
declare function fn(): FnResult;
declare namespace fn {
    export var fn: typeof globalThis.fn;
    var _a: typeof globalThis.fn;
    export { _a as default };
}

但是,在打字稿中使用 import fn from './mod'; 时,包括模块自己的单元测试,我收到 File '.../mod.ts' is not a module.ts(2306) 作为智能感知错误。这种“技术”是否还有更多内容,我缺少将其定义为模块但仍确保兼容性的方法

解决方法

看起来我可以通过使用 babel-plugin-replace-ts-export-assignment 在我的 babel 配置中解决这个问题。附加我的 saved_state=$(shopt -p) shopt -s extglob files=("$folder"-+([[:digit:]])-something) eval "$saved_state" 喜欢:

.babelrc

我的 "plugins": [ "babel-plugin-replace-ts-export-assignment" ] 然后看起来像:

app.ts

它现在可以正确构建 javascript commonjs 模式,而且我的 typescript 单元测试不会引发智能感知错误。

相关问答

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