【问题标题】:tsc not reporting errors when compilingtsc 编译时不报告错误
【发布时间】:2017-01-08 00:00:55
【问题描述】:

我在弄清楚一个神秘的情况时遇到了一些问题

我有一个 tsconfig 文件:

{
  "compilerOptions": {
    "outDir": "./built",
    "allowJs": true,
    "target": "es5"
  },
  "include": [
    "./app/**/*.ts"
  ]
}

当我使用下面的代码执行 tsc 时,这显然是错误的:

const credentials = Config.blahblah
import Config from '../../../config'

我知道这是错误的,因为 Config 不是在使用之前而是在之后导入的。

如果我切换这两行,那么代码通过了我的测试。但问题是,如果我保持上述顺序(这应该会给我一个错误),当我这样做时

mocha --compilers ts:ts-node/register,tsx:ts-node/register app/**/index-test.ts

甚至

tsc

例如:

➜  GhostFaceRestful git:(exie/workon_typescript) ✗ mocha --compilers ts:ts-node/register,tsx:ts-node/register app/**/index-test.ts
➜  GhostFaceRestful git:(exie/workon_typescript) ✗

根本没有错误消息。这使得调试非常困难。我想知道我做错了什么?至少 tsc 应该告诉我这种情况下存在编译错误?

【问题讨论】:

    标签: javascript typescript mocha.js tsc


    【解决方案1】:

    那是因为它不是 TypeScript 错误,因为 ES6(以及,我想,TypeScript)import 语句被提升了。 (您可以通过运行 tsc 来验证这一点 - 它也不会报告错误。)

    有趣的是,当它被编译时,require 调用并没有被提升。所以这个:

    const credentials = Config.blahblah
    import Config from '../../../config'
    

    变成这样:

    "use strict";
    var credentials = Config.blahblah;
    var Config = require('../../../config');
    

    您应该会看到运行时错误:

    TypeError: Cannot read property 'Config' of undefined
    

    如果要验证ts-node 是否报告了 TypeScript 编译错误,请使用明显的 TypeScript 错误;像这样:

    const n: number = "not-a-number";
    

    【讨论】:

    • 好吧,当module 设置为 commonjs 时,typescript 编译器可能会将其报告为“变量在初始化之前使用”错误。该代码应该可以与任何其他模块系统一起正常工作。
    • @artem 是的。可以,但不能。
    猜你喜欢
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 2018-03-10
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    相关资源
    最近更新 更多