Reputation: 103
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
Reputation: 4306
There is no way to do this with a single import statement.
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.
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));
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