Angular / Typescript - 通配符模块声明

问题描述 投票:7回答:1

我正在尝试实现通配符模块,我似乎没有得到它的工作:

现在我有以下代码可行:

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):enter image description here

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

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'...”
  • “未找到模块:错误:无法解决'静态'...”
  • “找不到模块:错误:无法解决'文字'...”

这个功能的一个例子是here,当它首次在Angular 2上实现时,

知道我做错了什么?

angular typescript angular6 angular7 angular-module
1个回答
0
投票

根据您分享的stackblitz code link,“静态”和“模板”目录不存在。只需创建目录并将数据放入其中。还要更新导入并从路径中删除!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);

  }
}

typings.d.ts

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

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

stackblitz链接

Here是您的代码的一个工作示例

© www.soinside.com 2019 - 2024. All rights reserved.