11

我正在尝试实现通配符模块,但似乎无法正常工作:

现在我有以下代码有效:

打字.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;
  }
}

您可能会在此处看到一个实时示例,但我想实现WILDCARDS,如此(typescriptlang)和此处(sitepen)所示: 在此处输入图像描述

实施应该允许我做这样的事情:

打字.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 ...”
  • “未找到模块:错误:无法解析 'static' in ...”
  • “找不到模块:错误:无法解析...中的'文本'”

当它首次在 Angular 2 上实现时,此功能的一个示例在这里,

知道我做错了什么吗?

4

1 回答 1

-1

根据您共享的stackblitz 代码链接,“静态”和“模板”目录不存在。只需创建目录并将数据放入其中。还要更新您的导入并从路径中删除!i18n或删除。!static

import * as es from './i18n/es.json';
import * as someObject from './static/someObject.json';

我只用 static/someObejcts 进行了测试。模板也将以相同的方式工作。

app.component.ts

import { Component, OnInit } from '@angular/core';
import * as es from './i18n/es.json';
import * as someObject from './static/someObject.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;
    console.log(es.default.hello);
    console.log(someObject.default.hello);

  }
}

打字.d.ts

declare module "*.json!i18n" {
  const value: any;
  export default value;
}

declare module "*.json!static" {
  const value: any;
  export default value;
}

堆栈闪电链接

是您的代码的工作示例

于 2018-10-02T14:54:00.333 回答