简体   繁体   English

js模块声明中的“文件不是模块”

[英]“File is not a module” on js module declaration

https://github.com/mgumerov/angular https://github.com/mgumerov/angular

Please have a look at src/mock-data/mock-data.js - it's big but very simple. 请查看src / mock-data / mock-data.js-它很大但是很简单。

System.register([], function (exports) {
  mockdata = {......};
  exports("MockData", mockdata);
});

I chose to consume it in my TS module src/app/table-view.ts: 我选择在TS模块src / app / table-view.ts中使用它:

import { MockData } from 'mockdata/mock-data';

but TSC gave me an error message because importing a JS module results in implicit 'any' object, unless the module has a TS typed declaration handy. 但是TSC给我一个错误消息,因为导入JS模块会导致隐式的“ any”对象,除非该模块方便使用TS类型的声明。 And, as Angular 2 quickstart suggests, "implicit any" are treated as errors. 而且,正如Angular 2快速入门所建议的那样,“隐式任何”都被视为错误。

My initial impulse was to use require() to import the module instead, as some sources propose. 我最初的冲动是改为使用require()来导入模块,如某些资料所述。 However that leads to error "cannot find name: require". 但是,这会导致错误“找不到名称:要求”。

All right, let's supply a declaration: src/mock-data/mock-data.d.ts 好吧,让我们提供一个声明:src / mock-data / mock-data.d.ts

declare module 'MockData' {
  var mockdata: any;
  export = mockdata;
}

It looks perfectly like other similar declarations ( https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/adal/index.d.ts ), except of course it's very simple because I only declare a single untyped object. 它看起来很像其他类似的声明( https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/adal/index.d.ts ),当然,这非常简单,因为我只声明了一个未类型化的对象。 And maybe I even don't do that properly, but that not the whole story! 也许我什至没有正确地做到这一点,但这还不是全部! Problem is, TSC now says TS2306: File ...mock-data.d.ts is not a module! 问题是,TSC现在说TS2306:File ... mock-data.d.ts不是一个模块! And even when I tried to replace the file with the one mentioned before (from DefinitelyTyped), the message remained the same. 即使当我尝试用前面提到的文件(来自DefinitelyTyped)替换文件时,消息仍然相同。 What is going on? 到底是怎么回事?

And where am I supposed to find a proper explanation of how to consume a JS module in TS? 我应该在哪里找到有关如何在TS中使用JS模块的适当解释? A module with no classes, no interfaces, just a single object? 没有类,没有接口,只有一个对象的模块?

Here is the proper declaration: 这是正确的声明:

export const MockData: any;

That's the whole mock-data.d.ts The MockData here is the identifier under which the export is made in my mock-data.js 这就是整个模拟数据.d.ts这里的MockData是我的模拟数据.js中进行导出的标识符

This is devised from https://www.typescriptlang.org/docs/handbook/modules.html - unfortunately the hint is hidden in a section "UMD modules", because in other examples there exist that "declare" thing which is not needed in my case. 这是从https://www.typescriptlang.org/docs/handbook/modules.html设计的-不幸的是,该提示隐藏在“ UMD模块”部分中,因为在其他示例中,存在“不需要声明”的内容就我而言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM