kogosoftwarellc / open-api

A Monorepo of various packages to power OpenAPI in node
MIT License
892 stars 235 forks source link

fs-routes: Also search for cjs files (#692) #693

Closed w3nl closed 3 years ago

w3nl commented 3 years ago

This code fixes #692 So if you use express-openapi or another package, you can run it in ES Modules modus. If you dont's use cjs for the files, the require in openapi-framework doesnt work, because require must return a CommonJS module, and in ES Modules modus you should use the .cjs extension. It is a very small fix, but very usefull.

If i change it to .cjs without this fix, the files are not found.

If i change the files to .js in ES Modules modus, you get this error:

(Use `node --trace-warnings ...` to show where the warning was created)
internal/modules/run_main.js:54
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: .../api-routes/example.js
require() of ES modules is not supported.
require() of .../api-routes/example.js from node_modules/openapi-framework/dist/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename users.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1216:13)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Module.require (internal/modules/cjs/loader.js:1089:19)
    at require (internal/modules/cjs/helpers.js:73:18)
    at node_modules/openapi-framework/dist/index.js:141:37
    at Array.map (<anonymous>)
    at node_modules/openapi-framework/dist/index.js:137:26
    at Array.forEach (<anonymous>)
    at OpenAPIFramework.initialize (node_modules/openapi-framework/dist/index.js:122:19) {
  code: 'ERR_REQUIRE_ESM'
}

If you have a solution that it import all routes as ES Modules, that would be great, and better than this fix, because now all routes are still CommonJS.