lukeautry / tsoa

Build OpenAPI-compliant REST APIs using TypeScript and Node
MIT License
3.32k stars 481 forks source link

CLI cannot import tsoa-config.js in ESM project #1630

Closed rdsfj closed 1 month ago

rdsfj commented 1 month ago

Sorting

Expected Behavior

In an ESM project with "type": "module" using tsoa, the CLI should be able to import tsoa-config.js or tsoa-config.cjs.

Current Behavior

I'm converting a project using tsoa from CJS to ESM. The project has its tsoa config not as JSON, but in tsoa-config.js. After moving to ESM and adding "type": "module" in package.json, the tsoa CLI breaks because it tries torequire the config. The CLI itself is a CJS package, but tsoa-config.js is now considered ESM by node because of type: module. Here's the actual code that fails and here's the same from the CLI's bundle:

else if (ext === '.js') {
    config = await Promise.resolve(`${`${workingDir}/${configPath}`}`).then(s => __importStar(require(s)));
}
else {
    const configRaw = await (0, fs_1.fsReadFile)(`${workingDir}/${configPath}`);
    config = JSON.parse(configRaw.toString('utf8'));
}

A solution is renaming tsoa-config.js to tsoa-config.cjs to force CJS and make the CLI's require work. However, as we can also see in the snippet above, the CLI doesn't recognise the .cjs extension as JS. Instead, it falls back to parsing the file as JSON, resulting in another error.

Possible Solution

The CLI could simply accept .js and .cjs extensions for JS config files. I'd be glad to contribute a MR to solve this!

Steps to Reproduce

Here's a small repo with instructions to reproduce the issue. https://github.com/rdsfj/tsoa-cli-repro

Context (Environment)

Version of the library: 6.2.1 Version of NodeJS: tested with 20.7.0 and 22.1.0

Detailed Description

Breaking change?

no

github-actions[bot] commented 1 month ago

Hello there rdsfj 👋

Thank you for opening your very first issue in this project.

We will try to get back to you as soon as we can.👀

rdsfj commented 1 month ago

Created a fix in PR #1634.