Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import native node modules correctly in Typescript

I've been using node for quite a while now (for my backends) and typescript with ionic (for frontend). On Ionic i realize I have managed to avoid many pitfalls and errors just because of TypeScript. I have hence decided to convert all my backends that are in pure JS to TypeScript.

The first obstacle I've run into is how to import native node modules like http, os and child_process, among others, correctly.

On most modules you can usually do something like import { some_export } from 'that_module'. I can also see the type definitions for node in the @types/ repo. I've tried import { http, os } from 'node' but I get a complaint that

/node_modules/@types/node/index.d.ts is not a module

My question hence is how should I import native node modules?

like image 201
davejoem Avatar asked Jan 25 '18 08:01

davejoem


People also ask

How do I import a custom module in TypeScript?

The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum. When exporting a module using export = , TypeScript-specific import module = require("module") must be used to import the module.

When using TypeScript where should you import modules from?

Use import myFunction from "./myModule" to bring it in. More commonly, TypeScript modules say export myFunction in which case myFunction will be one of the properties on the exported object. Use import { myFunction } from "./myModule" to bring it in.


1 Answers

I've managed to solve this issue thanks to some light reading from this simple tutorial

To my understanding, the native modules are standalone modules that are not namespaced under node. You should therefore import from them directly.

Simply done so:

import * as http from "http";
import * as os from "os";
import * as path from "path";
.
.
.
and so on
like image 177
davejoem Avatar answered Oct 21 '22 13:10

davejoem