【问题标题】:Import template in typescript without require在打字稿中导入模板而不需要
【发布时间】:2017-02-23 22:13:22
【问题描述】:

我正在使用带有 angular 1.5 组件的打字稿。我有一个定制设计的装饰器,我通过 require 发送模板。它有效,除了我收到一个 tslint 警告。 (我不想关闭这条规则)

require() 样式导入被禁止

这是我的组件

import './main.template.html';

const app: ng.IModule = angular.module('app');
@Component(app, {
  selector: 'mainComponent',
  controllerAs: 'ctrl',
  styleUrls: '',
  template: require('./main.template.html')
})
class MainComponent extends BaseComponent {
   constructor() {
     super();
   }
}

这是我的装饰器

export const Component = function(module: ng.IModule, options: {
  selector: string,
  controllerAs?: string,
  styleUrls?: string,
  template?: string,
  templateUrl?: string
}) {
return (controller: Function) => {
   module.component(options.selector, angular.extend(options, {  controller: controller }));
  };
};

我尝试传递 templateUrl 而不是模板,但我得到了找不到文件的运行时错误。

我也尝试将模板作为变量导入,但它给出了编译时错误,并且看起来不受支持。

import mytemplate: string from './main.template.html';

我正在使用 webpack。因此,不能使用从根目录开始的绝对路径。

你知道如何在不使用 require 的情况下在 typescript 中导入模板吗?

【问题讨论】:

  • 导入模板时会出现错误吗

标签: angularjs typescript import ecmascript-6


【解决方案1】:

对于 templateUrl 错误,请检查您的参考和目录结构。

或者,在模板中插入 html 数据:-

@Component(app, {
selector: 'mainComponent',
controllerAs: 'ctrl',
styleUrls: '',
template: `<div>//content
           </div>`
})

【讨论】:

  • 我正在使用 webpack 构建,因此没有模板文件或目录结构。
  • 把你的模板和 webpack build.js 放在同一个目录下,也许 templateUrl 从你的 build.js 的目录来源引用文件
  • 这行得通。但是,我必须将所有模板(对于目录中的每个组件)。我担心的是,在使用 webpack 作为构建工具时,这可能不是最佳实践
猜你喜欢
  • 2018-05-22
  • 2019-04-12
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
  • 2017-02-01
  • 1970-01-01
相关资源
最近更新 更多