I've been facing challenges while updating some JavaScript modules to TypeScript while maintaining compatibility with older projects. These older projects utilize the commonjs pattern const fn = require('mod');
, which I still need to accommodate. I have been referencing the TypeScript guide for handling various types of imports which has been helpful:
// src/mod.ts
type FnResult = Promise<void>;
function fn(): FnResult {
return Promise.resolve();
}
fn.fn = fn;
fn.default = fn;
module.exports = fn;
So far, this method works well for compiling to both older and newer JavaScript projects using tsc
. The output looks like this:
// 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 };
}
However, when I try to use import fn from './mod';
in TypeScript, including within the module's own unit tests, I encounter the error
File '.../mod.ts' is not a module.ts(2306)
in the Intellisense. Is there something crucial I might be overlooking in defining this as a module while maintaining compatibility?