I'm trying to get this to work, but I can't seem to find a solution anywhere on SO. When trying to compile this single-file app:
import http = require('http') http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/');
Using the command "tsc app.ts --module 'commonjs'" I get the following error (not using the --module flag gives me an additional error telling me that I need it to compile external modules):
error TS2071: Unable to resolve external module '"http"'. error TS2072: Module cannot be aliased to a non-module type.
Approach: Before importing any module we need to export it from another file. We can create a module by using the export keyword and can use it in other modules by using the import keyword. We can export both class-based modules and function-based modules. as shown below.
To import all modules from a directory in TypeScript, we can create a module that reexports all modules that were imported. export { default as A } from "./a"; export { default as B } from "./b"; to import the default exports from modules a and b .
Importing Types With TypeScript 3.8, you can import a type using the import statement, or using import type .
TypeScript needs to know that http
is present.
Install the type definitinos for node:
npm install @types/node
Follows these two steps
node.d.ts
file from here : https://github.com/borisyankov/DefinitelyTyped/tree/master/node At the top of your file add:
/// <reference path="node.d.ts" />
PS: See a sample test file : https://github.com/borisyankov/DefinitelyTyped/blob/master/node/node-tests.ts
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