如何在 Typescript 项目中正确导入命名空间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39472166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to properly import a namespace in a Typescript project?
提问by skiabox
I am watching a video tutorial and I have created a a new typescript project. First I created in the root directory the following namespace (utilityFunctions.ts) :
我正在观看视频教程,并且创建了一个新的打字稿项目。首先,我在根目录中创建了以下命名空间 (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...');
}
}
Then I created another typescript file (app.ts) to use the above namespace code :
然后我创建了另一个打字稿文件(app.ts)来使用上面的命名空间代码:
/// <reference path="utilityFunctions.ts" />
let fee: number = Utility.Fees.CalculateLateFee(10);
console.log(`Fee: ${fee}`);
When I run the app.js file (using webstorm latest version) I am getting the following error :
当我运行 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
My tsconfig.json file is the following :
我的 tsconfig.json 文件如下:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": true
},
"exclude": [
"node_modules"
]
}
And my tslint.json file is the following (although I don't think that the linter has anything to do with compilation errors):
我的 tslint.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"
]
}
}
回答by Nitzan Tomer
As your utilityFunctions.ts
is already a module then there's no need to wrap what's inside of it in a namespace.
由于您utilityFunctions.ts
已经是一个模块,因此无需将其中的内容包装在命名空间中。
Also, using /// <reference ...
is just for the compiler but node won't use it and so it doesn't know where to find utilityFunctions
.
You need to import it.
此外, using/// <reference ...
仅用于编译器,但 node 不会使用它,因此它不知道在哪里找到utilityFunctions
.
你需要导入它。
Here are how the files should look:
以下是文件的外观:
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...');
}
And:
和:
/// <reference path="utilityFunctions.ts" />
import * as Utility from "./utilityFunctions"
let fee: number = Utility.Fees.CalculateLateFee(10);
console.log(`Fee: ${fee}`);
You can also completely remove the /// <reference
as the compiler can find the .ts
file when importing.
您也可以完全删除 ,/// <reference
因为编译器可以.ts
在导入时找到该文件。
回答by TJ Rockefeller
Typescript transpiles to javascript, and since javascript is not a compiled language, you need to run or load all of your javascript files in order if one is dependent on the other.
Typescript 转换为 javascript,并且由于 javascript 不是编译语言,如果一个依赖另一个,您需要按顺序运行或加载所有 javascript 文件。
Namespaces are basically global objects in javascript, so they need to be defined and loaded before they are used.
命名空间在 javascript 中基本上是全局对象,因此在使用它们之前需要定义和加载它们。
In a web page the loading is typically specified with script tags like such in the main html file.
在网页中,加载通常使用脚本标签指定,例如在主 html 文件中。
<script src="utilityFunction.js"></script>
<script src="app.js"></script>
This will load the utilityFunction file first and define the object/namespace Utility
so that when app.js
runs it will have visibility of the object Utility
这将首先加载utilityFunction文件并定义对象/命名空间,Utility
以便在app.js
运行时它具有对象的可见性Utility
I'm not really sure how WebStorm works, but it's likely that you need to define somewhere in your project what files are loaded and in what order.
我不太确定 WebStorm 是如何工作的,但您可能需要在项目中的某处定义加载哪些文件以及加载顺序。
回答by Mark Macneil Bikeio
Quick And Easy in Visual Studio
在 Visual Studio 中快速简便
Drag and Dropthe file with .ts extension from solution window to editor, it will generate inline reference code like..
将扩展名为 .ts 的文件从解决方案窗口拖放到编辑器,它将生成内联参考代码,如..
/// <reference path="../../components/someclass.ts"/>