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?
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.
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.
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
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