In TypeScript, what is the difference between
import http = require('http');
and
var http = require('http');
I am seeing both ways being used in code source, are they interchangeable?
To import a variable from another file in TypeScript: Export the variable from file A , e.g. export const str = 'hello world' . Import the variable in file B as import { str } from './another-file' .
Importing TypesWith TypeScript 3.8, you can import a type using the import statement, or using import type .
import type only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there's no remnant of it at runtime. Similarly, export type only provides an export that can be used for type contexts, and is also erased from TypeScript's output.
One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with .
Your import
statement is TypeScript and will not run as-is in Node. You will need to compile (transpile?) it to JavaScript first. You can read the TypeScript docs for more info about how the TypeScript import
keyword works. See the "Using Modules" subsection of the "Namespaces and Modules" section of the TypeScript handbook.
There is an import
keyword in JavaScript too, but it doesn't work the way TypeScript's import
works. It will only work in versions of Node that support ES6 modules. There are differences between this import
and require
that you can read about at "ES6 Modules: The Final Syntax". That import
is something you can compare/contrast with require
but not really var
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With