【问题标题】:Writing Typescript for Many Import Patterns and Intellisense为许多导入模式和智能感知编写 Typescript
【发布时间】:2021-02-16 18:13:38
【问题描述】:

我正在尝试将一些 javascript 模块更新为 typescript,但无法保持兼容性。我有一些使用 commonjs 模式 const fn = require('mod'); 的 javascript 中的旧项目仍然依赖于这个模块。我已经尝试按照 typescript guide 处理这么多类型的导入:

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) 作为智能感知错误。我缺少将其定义为模块但仍确保兼容性的这种“技术”吗?

【问题讨论】:

    标签: typescript commonjs


    【解决方案1】:

    看起来我可以在我的 babel 配置中使用 babel-plugin-replace-ts-export-assignment 解决这个问题。附加我的.babelrc 喜欢:

    "plugins": [
      "babel-plugin-replace-ts-export-assignment"
    ]
    

    我的app.ts 然后看起来像:

    fn.fn = fn;
    fn.default = fn;
    export = fn;
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 2022-07-04
      • 2018-02-24
      • 2017-03-28
      • 1970-01-01
      • 2020-11-13
      • 2017-02-15
      相关资源
      最近更新 更多