Nasser Alghamid
Nasser Alghamid

Reputation: 103

How to write require that takes an argument in typescript?

I want to import a module that takes an argument in Typescript. I have this written in javascript:

const cors = require('cors')({origin: true}); // JS

How can I write the same expression in Typescript?

Upvotes: 5

Views: 1349

Answers (1)

Trent
Trent

Reputation: 4306

There is no way to do this with a single import statement.

What is that unusual require statement doing?

This can be better understood if you decompose the require statement.

When you write const cors = require('cors')({origin: true});, what you are actually doing is as follows:

const corsPackage = require('cors');
const cors = corsPackage({origin: true});

Notice that you're simply importing the package, then initializing it.


Solution

The proper way to rewrite this in ES6 / TypeScript is as follows:

First import the desired package:

import cors from 'cors';

Now you can either initialize cors inline, or assign it to a variable:

// Assigning the initialized `cors` package to a variable
const allowCors = cors({origin: true});

// OR, initialize it as the point of usage. For example, with express:
router.use(cors(options));

Why was this so difficult to find the answer for?

The reason you're not seeing this method importing the cors package in its documentation using the ES6 import statement is because the package is meant to be used with Node on the backend; and not in the browser.

Until Node v10.0 LTS is released, you will need to use the --experimental-modules flag to use this feature.


Your question is referring to using the ES6 import statement; which is not TypeScript specfic, but instead is a feature you inherit because of TypeScripts transpilation to browser-compatible code.

Upvotes: 3

Related Questions