Markus Mauch
Markus Mauch

Reputation: 1283

How to use TypeScript definition files from the @types npm repository when --module is 'none'

how can I use TypeScript definition files via @types if the compiler's module system parameter is set to 'none'? For example, when using the type definitions for the express web server:

npm install @types/express

with the following tsconfig.json

{
    "compilerOptions":
    {
        "module": "none"
    }
}

This code fails:

import * as express from "express";

export module Web.Server
{
    const app = express();
}

with the error message:

Cannot use imports, exports, or module augmentations when '--module' is 'none'.

If it is not possible to use type definition files in an non-module environment, what is best practice to cope with this situation?

Thanks in advance...

Upvotes: 3

Views: 929

Answers (2)

qwabra
qwabra

Reputation: 2194

typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html

main.d.ts

export as namespace _dependencies;//from MAIN to MAIN didn't work, need reference

import * as _fs from 'fs'
import * as _path from 'path'
import * as _socket from 'socket.io'
import * as _http from 'http'
import * as _child from 'child_process'

export const fs: typeof _fs
export const path: typeof _path
export const socket: typeof _socket
export const http: typeof _http
export const child: typeof _child

main.ts

/// <reference path="main.d.ts" />
namespace MAIN {
    export const fs: typeof _dependencies.fs = require("fs")
    export const path: typeof _dependencies.path = require("path")
    export const socket: typeof _dependencies.socket = require("socket.io")
    export const http: typeof _dependencies.http = require("http")
    export const child: typeof _dependencies.child = require("child_process")
}

namespace MAIN {
    export module a {
        export function start(_serverPort = 8080) {
            const server = http.createServer(function requestListener() { })
            const io = socket(server);
            server.listen(_serverPort);
            return { io, _serverPort };
        }
    }
}
namespace MAIN {
    export module b { /* ... */ }
}

https://github.com/Microsoft/TypeScript/issues/17279#issuecomment-316228569

Upvotes: 0

Kirill Dmitrenko
Kirill Dmitrenko

Reputation: 3629

You can "import" it with /// reference directive:

/// <reference path="./node_modules/@types/lodash/index.d.ts" />

console.log(_);

Upvotes: 2

Related Questions