Search code examples
importtypescriptmodulerequirejscommonjs

TypeScript: Avoid require statements in compiled JavaScript


In my TypeScript code I am using a third-party library called bunyan like so:

private logger: bunyan.Logger = bunyan.createLogger({name: "MyClass"});

Because TypeScript cannot resolve the variable bunyan, I do this to make the TypeScript compiler work:

import * as bunyan from "bunyan";

Unfortunately this causes the following JavaScript output:

var bunyan = require("bunyan");

The require statement will not work in the browser (when not using a requirejs implementation), so I will receive: Uncaught ReferenceError: require is not defined.

Actually I don't need the require statement in my compiled JavaScript because there is a bunyan.min.js (browserified version) which I can use for the browser. But how can I avoid the bunyan import in my TypeScript code without having the TypeScript compiler complaining about an unknown reference?

I am using TypeScript 1.8 and this is my TypeScript compiler configuration:

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitAny": false,
    "removeComments": true,
    "target": "es5"
  },
  "exclude": [
    "node_modules",
    "typings/browser",
    "typings/browser.d.ts"
  ]
}

Solution

  • You should use declare to declare a module for bunyan with Logger and createLogger.

    declare module bunyan {
        export interface Logger {
            info(message: string): any;
            warn(message: string): any;
        }
    
        export function createLogger(options: any): Logger;
    };
    
    class MyClass {
        private logger: bunyan.Logger = bunyan.createLogger({name: "MyClass"});
    }
    

    I would recommend using a typings declaration file like the one found here so you get the full benefit of TypeScript :)