typescript – Webpack + TS: Can’t make Node.js happy with ‘module’ or ‘commonjs’ type

This is my first time setting up Webpack manually, and Typescript is in the mix.

The project builds successfully, but when running the build with yarn start there’s the following error:

Error [ERR_REQUIRE_ESM]: require() of ES Module C:UserskarloProjectsreports_servernode_modulesopenaidistindex.js from C:UserskarloProjectsreports_serverdistserver.js not supported.

The error is thrown by this line module.exports = require("openai"); in the output server file. The original .ts files use ES6 imports, but it seems TS or Webpack automatically convert these to CommonJS. Pressing on, let’s follow the advice seen online for this error:

Modify package.json to include "type": "module"

Oh boy. Now the following error pops up:

ReferenceError: require is not defined in ES module scope, you can use import instead

That’s being thrown by this line: module.exports = require("apollo-server");

The same syntax as the line causing the previous error, and actually just above it in the code.

I’m feeling quite stuck in the middle and kicking myself for not using boilerplate… but at the same time really want to understand where things have gone wrong. If you feel you might know and need more info, please say so.

Read more here: Source link