0

I have a nodejs project writing in typescript. In some ts file I use require and import together, e.g. when using debugjs because it has cjs module only. I know there is @types/debug but since debugjs usage is rather straightforward I don't bother to use it. But expressjs is another story because I feel @types/express can help me better use express.

I know the difference between cjs and ej module, e.g. as Using Node.js require vs. ES6 import/export discussed, but since my ts files will be transpiled into cjs running inside nodejs (I don't use mjs or set "type": "module" in package.json), what is the problem is mixing require and import in the same typescript file?

So far I have not noticed any problem.

Qiulang
  • 10,295
  • 11
  • 80
  • 129

1 Answers1

2

Cases where it is necessary to use bothrequire and import in a single file, are quite rare and it is generally not recommended and considered not a good practice. However, sometimes it is the easiest way for us to solve a problem. There are always trade-offs and the decision is up to you. But, If you use ES6 module, recommended using import.

Additionally, the difference between commonJS require and ES6 import is

  • With require, cannot load pieces you need to load, but with import, you can selectively load only the pieces you need, which can save memory.
  • Regarding performance, import is a little faster/better than require since it is asynchronous, but require is synchronous.
ClusterH
  • 761
  • 3
  • 16
  • But in the end all ts files will be transpiled into cjs js files run in nodejs, so I really doubt these points are valid. – Qiulang Dec 06 '22 at 01:20
  • "import is a little faster/better than require since it is asynchronous" --- what this statement is based on? asynchronisity does not make anything quicker (it's actually the opposite). – zerkms Dec 06 '22 at 03:50
  • Loading is synchronous(step by step) for `require` on the other hand `import` can be asynchronous(without waiting for previous import) so it can perform a little better than `require`. – ClusterH Dec 06 '22 at 05:48
  • Even this is the case for a server side app, it really doesn't matter – Qiulang Dec 06 '22 at 07:22