I have changed the code of a project made in NodeJS to Typescript.
Everything is working fine, except for the fact that apparently a third-part package (file-type, https://www.npmjs.com/package/file-type) does not seem to accept the require
that is generated in the compiled .js
files.
To change that, I have to change the "module" property of tsconfig.json to another value other than "commonjs". However, it breaks the code and generates a lot of problems.
My tsconfig.json:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"allowJs": true,
"lib": ["ES6"],
"esModuleInterop": true,
"moduleResolution": "node",
"outDir": "build",
"rootDir": "src",
"skipLibCheck": true,
"strict": true
}
}
The error I get:
const filetype = __importStar(require("file-type"));
^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\user\Desktop\repos\art-api\node_modules\file-type\index.js from C:\Users\user\Desktop\repos\art-api\build\middlewares\process-image.js not supported.
Instead change the require of index.js in C:\Users\user\Desktop\repos\art-api\build\middlewares\process-image.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (C:\Users\user\Desktop\repos\art-api\build\middlewares\process-image.js:33:31)
at Object.<anonymous> (C:\Users\user\Desktop\repos\art-api\build\controllers\artworkControllers.js:19:25)
at Object.<anonymous> (C:\Users\user\Desktop\repos\art-api\build\routers\artworkRouter.js:7:30)
at Object.<anonymous> (C:\Users\user\Desktop\repos\art-api\build\server.js:9:41) {
code: 'ERR_REQUIRE_ESM'
}
Apparently, the problem is that the code generated in JavaScript conflicts with the code of the package, that uses the ES6 export syntax. If this is correct, how can I fix this issue? Is there a way to generate .js code with import syntax only for this particular package, or some workaround like that? Other parts of the code don't give me any problems, only the import of this package(file-type).
Just in case, this is the index.js of 'file-type', where it has the import the compiler is complaining about:
import * as strtok3 from 'strtok3';
import {fileTypeFromTokenizer} from './core.js';
export async function fileTypeFromFile(path) {
const tokenizer = await strtok3.fromFile(path);
try {
return await fileTypeFromTokenizer(tokenizer);
} finally {
await tokenizer.close();
}
}
export * from './core.js';