Home > Software engineering >  How to configure TS to allow imports from CJS to ES modules (node-fetch & Express)?
How to configure TS to allow imports from CJS to ES modules (node-fetch & Express)?

Time:11-21

I am trying to get two libraries to run in one project: fetch-node, which is an ES module, and Express, which is CommonJS. The problem is that I have to import fetch-node like so:

import fetch from 'node-fetch';

but Express requires me to import it like so:

const express = require('express')

which is not possible with my config, package.json: "type": "module", and tsconfig.json:

"target": "es2016",   
"lib": ["es2019"],    
"module": "Node16",    
"esModuleInterop": true,

So when I import Express like described, I get this error:

const express = require('express');
                ^

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/mnt/c/Users/Johannes/citygmlToGltf/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///mnt/c/Users/Johannes/citygmlToGltf/bin/app.js:15:17
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)

Node.js v19.1.0
error Command failed with exit code 1.

What is the trick here? Can I not use these two libraries together in one project?

CodePudding user response:

The problem I was facing did come from the tsconfig. I had to add:

"moduleResolution": "node", 

to be able to use both require() and dynamic import like import * from "asdf"

  • Related