TypeScript:避免在已编译的JavaScript中使用require语句 [英] TypeScript: Avoid require statements in compiled JavaScript

查看:474
本文介绍了TypeScript:避免在已编译的JavaScript中使用require语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的TypeScript代码中,我正在使用名为 bunyan 的第三方库,如下所示:

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

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

因为TypeScript无法解析变量bunyan,所以我这样做是为了使TypeScript编译器正常工作:

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

import * as bunyan from "bunyan";

不幸的是,这会导致以下JavaScript输出:

Unfortunately this causes the following JavaScript output:

var bunyan = require("bunyan");

require语句在浏览器中不起作用(当不使用 requirejs 实现时),因此我将收到:Uncaught ReferenceError: require is not defined.

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.

实际上,我在编译的JavaScript中不需要require语句,因为有一个bunyan.min.js(浏览器版本),可以用于浏览器.但是,如何在TypeScript编译器抱怨未知引用的情况下避免在我的TypeScript代码中导入bunyan?

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?

我正在使用TypeScript 1.8,这是我的TypeScript编译器配置:

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"
  ]
}

推荐答案

您应使用declare为具有LoggercreateLoggerbunyan声明模块.

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 :)

这篇关于TypeScript:避免在已编译的JavaScript中使用require语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆