如何在Typescript项目中正确导入命名空间

How to properly import a namespace in a Typescript project?

本文关键字:导入 命名空间 项目 Typescript      更新时间:2023-09-26

我正在看一个视频教程,我已经创建了一个新的打字项目。首先,我在根目录中创建了以下名称空间(utilityFunctions.ts):

namespace Utility {
    export namespace Fees {
        export function CalculateLateFee(daysLate: number): number {
            return daysLate * .25;
        }
    }
    export function MaxBooksAllowed(age: number): number {
        if (age < 12){
            return 3;
        }
        else {
            return 10;
        }
    }
    //function that is not exported
    //use it only inside the namespace
    function privateFunc(): void {
        console.log('This is private...');
    }
}
然后我创建了另一个typescript文件(app.ts)来使用上面的命名空间代码:
/// <reference path="utilityFunctions.ts" />

let fee: number = Utility.Fees.CalculateLateFee(10);
console.log(`Fee: ${fee}`);

当我运行app.js文件(使用webstorm最新版本)时,我得到以下错误:

/Users/Administrator/.nvm/versions/node/v6.5.0/bin/node /Users/Administrator/WebstormProjects/NamespaceDemo/app.js
/Users/Administrator/WebstormProjects/NamespaceDemo/app.js:5
var fee = Utility.Fees.CalculateLateFee(10);
                       ^
ReferenceError: Utility is not defined
    at Object.<anonymous> (/Users/Administrator/WebstormProjects/NamespaceDemo/app.js:5:24)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3
Process finished with exit code 1
我tsconfig

。Json文件如下:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": true
    },
    "exclude": [
        "node_modules"
    ]
}

还有我的衬衣。json文件如下(虽然我不认为linter与编译错误有任何关系):

{
    "extends": "tslint:recommended",
    "rules": {
        "comment-format": [false, "check-space"],
        "eofline": false,
        "triple-equals": [false, "allow-null-check"],
        "no-trailing-whitespace": false,
        "one-line": false,
        "no-empty": false,
        "typedef-whitespace": false,
        "whitespace": false,
        "radix": false,
        "no-consecutive-blank-lines": false,
        "no-console": false,
        "typedef": [true,
            "variable-declaration",
            "call-signature",
            "parameter",
            "property-declaration",
            "member-variable-declaration"
        ],
        "quotemark": false,
        "one-variable-per-declaration": false,
        "max-line-length": 160,
        "object-literal-sort-keys": false,
        "trailing-comma": false,
        "variable-name": [true,
            "ban-keywords",
            "check-format",
            "allow-leading-underscore"
        ]
    }
}

由于您的utilityFunctions.ts已经是一个模块,因此没有必要将其内部的内容包装在命名空间中。

另外,使用/// <reference ...只是为了编译器,但节点不会使用它,所以它不知道在哪里找到utilityFunctions
你需要导入它。

文件应该是这样的:

export namespace Fees {
    export function CalculateLateFee(daysLate: number): number {
        return daysLate * .25;
    }
}
export function MaxBooksAllowed(age: number): number {
    if (age < 12){
        return 3;
    }
    else {
        return 10;
    }
}
//function that is not exported
//use it only inside the namespace
function privateFunc(): void {
    console.log('This is private...');
}

:

/// <reference path="utilityFunctions.ts" />
import * as Utility from "./utilityFunctions"
let fee: number = Utility.Fees.CalculateLateFee(10);
console.log(`Fee: ${fee}`);

您也可以完全删除/// <reference,因为编译器在导入时可以找到.ts文件。

Visual Studio Quick And Easy

扩展名为.ts的文件从解决方案窗口拖放到编辑器,它将生成内联引用代码,如..

/// <reference path="../../components/someclass.ts"/>

Typescript会被编译成javascript,因为javascript不是编译语言,如果一个javascript文件依赖于另一个,你需要按顺序运行或加载所有的javascript文件。

名称空间在javascript中基本上是全局对象,所以它们需要在使用之前被定义和加载。

在一个网页中,加载通常是用脚本标签指定的,就像在主html文件中一样。

<script src="utilityFunction.js"></script>
<script src="app.js"></script>

这将首先加载utilityFunction文件并定义对象/命名空间Utility,以便当app.js运行时,它将能够看到对象Utility

我不太确定WebStorm是如何工作的,但很可能你需要在项目的某个地方定义加载哪些文件以及以什么顺序加载。