Nemus
Nemus

Reputation: 1482

Import and require used together

Recently I come into this:

import foo = require("/foo");

This sound me really weird, as I usually use require like this:

var foo = require("/foo");

Or import like this:

import foo from "/foo";

So, what's the point of that?

Upvotes: 4

Views: 3052

Answers (2)

Sebastian Sebald
Sebastian Sebald

Reputation: 16856

The statements import {foo} = require("/foo"); and var foo = require("/foo"); are not equivalent. Say /foo is a file with the following contents:

export default { bar: 'bar' };
export const foo = 'hello';

With the first statement your variable foo will be 'hello'. The {} is an object destructuring. In the other case you will receive the default exports, which means foo will be the object { bar: 'bar' }.

MDN has some good explanation: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/import

Upvotes: 0

Nitzan Tomer
Nitzan Tomer

Reputation: 164139

Checkout the export = and import = require() part of the docs:

When importing a module using export =, TypeScript-specific import let = require("module") must be used to import the module

You can write it like this as well:

import foo = require("/foo");

Upvotes: 1

Related Questions