我正在看一個視頻教程,並且我創建了一個新的打字稿項目。 首先我在根目錄中創建以下命名空間(utilityFunctions.ts):如何在Typescript項目中正確導入名稱空間?
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...');
}
}
然後創建另一個打字稿文件(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"
]
}
而且我tslint.json文件如下(雖然我不認爲棉短絨有什麼用編譯錯誤):
{
"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"
]
}
}
這可能是有益的,看看你的文件夾結構是什麼樣子。這可能是它無法找到該文件。我還沒有發現如何解決腳本標記的問題,但是您可能需要向您的tsconfig添加此編譯器選項「moduleResolution」:「node」我不確定,但這也可能會影響腳本標記解析。 –
Ok.Mystery解決了!我剛看了視頻的其餘部分,並得到了完全相同的錯誤。它是一個nodejs問題.NodeJS不接受多個文件中的命名空間(它只接受模塊 - 至少這是導師所說的),所以我必須將「outFile」這一行:「out.js」添加到我的tsconfig.json中,然後運行這個將所有項目的打字稿文件收集到一個JavaScript文件中的單個文件。 – skiabox