How to compile typescript to use CommonJS and import/export?

35 Views Asked by At

For example, I have an index.ts file in which a function that returns the sum of two numbers is exported via export. And also the test.js file which imports the function from the already compiled index.js file,how can I make it so that I can import the function through require and also import?

Example in index.ts:

export default (a: number, b: number): number => a + b;

And I need to be able to do this in test.js:

import num from "./index.js";
// OR
const num = require("./index.js");

How can I do this, maybe through a configuration file or a library, a framework, a piece of code?

1

There are 1 best solutions below

1
Malcolm Mutare On

To achieve compatibility for both CommonJS (Node.js require) and ES6 module syntax (import), you can do the following:

Use TypeScript tsconfig.json: In your tsconfig.json file, set the "module" option to "commonjs".

{ "compilerOptions": { "module": "commonjs", // other options... } }

Use module.exports in TypeScript: In your index.ts file, use module.exports along with the default export

const sum = (a: number, b: number): number => a + b;

export default sum; module.exports = sum;

// Using ES6 import import num from "./index";

// Using CommonJS require const num = require("./index");

This way, your TypeScript code is compatible with both ES6 modules and CommonJS, allowing you to use import and require interchangeably.