2016-10-02 45 views
0

我正在将JavaScript项目迁移到TypeScript。现有的JavaScript使用requirejs进行模块加载,并且我想在TypeScript中执行相同的操作。TypeScript与requirejs无法找到模块错误

我有一个模块在编译时从其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的配置文件。我可以将语言服务指向该文件以解决模块引用问题吗?我真的很想在设计时尽可能地分离文件路径中的引用。

回答

2

所以首先,对于类定义,你可以更新它们看起来像这样。

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

更多关于这个问题:

https://www.typescriptlang.org/docs/handbook/modules.html

-1

不要使用相对路径,即

“../../帮手”。

始终使用项目文件夹中的绝对路径即 “app/components/Helper”

另外,不要在文件路径前放置一个/,因为这可能会导致问题。

不要使用//参考,使用

import { myClass } from 'app/components/Helper'; 

这也将有助于捆绑JS的当requirejs找到类引用更容易。

弗拉德也正确,只是改变你的类定义太...

export class Helper { 
    [...] 
} 

你不需要出口=助手声明在文件的结尾。