【发布时间】:2019-02-21 17:27:44
【问题描述】:
我正在尝试实现通配符模块,但似乎无法正常工作:
现在我有以下有效的代码:
typings.d.ts
declare module "*.json" {
const value: any;
export default value;
}
app.component.ts
import { Component, OnInit } from '@angular/core';
import * as es from './i18n/es.json';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
hello = '-';
ngOnInit() {
this.hello = es.default.hello;
}
}
您可能会看到一个实时示例 here,但我想实现 WILDCARDS,如 here (typescriptlang) 和 here (sitepen) 所示:
实现应该允许我做这样的事情:
typings.d.ts
declare module "*.json!i18n" {
const value: any;
export default value;
}
declare module "*.json!static" {
const value: any;
export default value;
}
declare module "*!text" {
const value: any;
export default value;
}
app.component.ts
import { Component, OnInit } from '@angular/core';
import * as es from './i18n/es.json!i18n';
import * as someObject from './static/someObject.json!static';
import * as template1 from './templates/template1.html!text';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
hello = '-';
ngOnInit() {
this.hello = es.default.hello;
console.log(someObject.default);
console.log(template1.default);
}
}
问题是由于某种原因通配符没有被正确识别...在运行时抛出“json”未找到。
- “未找到模块:错误:无法解析 'json' in ...”
- “未找到模块:错误:无法解析...中的“静态””
- “未找到模块:错误:无法解析...中的‘文本’”
here 第一次在 Angular 2 上实现时,就是这个功能的一个例子,
知道我做错了什么吗??
【问题讨论】:
-
我正在删除我的答案,因为我发现它完全错误:通配符
declare module确实适用于 TypeScript 中的相对导入。我认为您的问题出在 webpack 配置上,但我对此知之甚少,无法提供帮助。 -
谢谢你,马特,我是这么想的,因为我试图实现你的答案但没有成功:(我还在想办法实现这个。
-
你不应该在你的导入中使用
!注解。它应该被提取到 webpack 配置中。您可能还想查看resolveJsonModuleflag -
你好@Ebuall,我已经在没有
!注释的情况下工作了,这个问题的原因是我想实现它,所以我可以分离每种不同类型的JSON文件,例如i18n JSON 的模块应该与此类似:declare module "*.json!i18n" { const value: any; export default value; export interface Language { [key: string]: any; }; }我将能够通过仅使用导入来封装 JSON 行为/接口。
标签: angular typescript angular6 angular7 angular-module