[英]TypeScript with requirejs cannot find module error
我正在將一個 JavaScript 項目遷移到 TypeScript。 現有的 JavaScript 使用 requirejs 進行模塊加載,我想在 TypeScript 中做同樣的事情。
我有一個模塊在編譯時從其import
語句中拋出“找不到模塊”錯誤。 我有正確的<reference/>
標簽,並且引用模塊將在運行時按預期工作。 但是,我想從我的錯誤列表窗口中清除這些錯誤的編譯器錯誤。
這是該模塊的基本文件結構及其引用:
root/
helper.ts
ui/
uiModule.ts //This module is throwing the error
panels/
panel1.ts //The import of this module throws the error
uiModule
的頂部看起來像這樣:
///<reference path="../helper.ts"/>
///<reference path="panels/panel1.ts"/>
import helper = require("Helper");
import panel1 = require("Panel1");
所有模塊都設置為單個類,如下所示:
//references and imports...
class MyClass {
//Methods...
}
export = MyClass;
所有文件名和import
別名都以小寫開頭; 所有類名都以大寫開頭。
“找不到模塊”錯誤似乎只發生在一個模塊在更深的文件夾中引用另一個模塊時。 如果我將import
語句更改為 `require("Panels/panel1"),編譯器錯誤就會消失,但它會在運行時失敗。
我怎樣才能正確地使這個錯誤停止出現? 我有一個 requirejs 的配置文件。 我可以將語言服務指向該文件以解析模塊引用嗎? 我真的很想在設計時盡可能地將引用與文件路徑分離。
因此,首先,對於類定義,您可以將它們更新為如下所示。
export class MyClass {
// TO-DO
}
至於 require 語句,編譯器告訴您它們找不到是正常的。
因此,鑒於您的文件結構,您的導入應如下所示:
import helper = require("../helper");
import panel1 = require("./panels/panel1");
或者
// remember you can have a file with multiple exported objects
// or and 'index.ts' file inside a folder which exports multiple files
// by using the import syntax you can choose what to import from that module
import { helper } from '../helper';
import { panel1 } from './panels/panel1';
這應該可以解決您當前的問題。
我正在與 TS 合作尋求幫助的示例項目:
https://github.com/vladjerca/imgstry/tree/feature/typescript_port
有關該主題的更多信息:
不要使用相對路徑,即
“../../幫手”。
始終使用項目文件夾中的絕對路徑,即“app/components/Helper”
也不要在文件路徑前面放置 / ,因為這可能會導致問題。
不要使用 // 引用,使用
import { myClass } from 'app/components/Helper';
這也將有助於 requirejs 在捆綁 js 時更容易地找到類引用。
Vlad 也是正確的,只需更改您的類定義...
export class Helper {
[...]
}
您不需要文件末尾的 export = Helper 語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.