angularjs - 在 typescript 中导入html模板

标签 angularjs typescript angular-routing webpack-3 typescript-2.5

我正在尝试导入 我的 html 模板,以便 webpack 能够识别它们并在我构建时包含它们。 (webpack -d)

根据 this GitHub issue我应该这样做

declare module '*.html' {
    const _: string;
    export default _;
}

然后 import template from './myTemplate.html'; 应该可以工作。

但这并不能完全解决问题。

import template from './myTemplate.html';
console.log(template); // undefined

然而这“有效”

import * as template from './myTemplate.html';
console.log(template); // <p>Hello world!</p>

很奇怪。

但是现在这行不通了

$routeProvider.when("/test", {
    template: template, // ERROR! template is typeof(*.html) expected string
    controller: MyController,
    controllerAs: "$ctrl"
});

但是,如果我将我的 *.html 模块更改为

declare module '*.html' {
    const _: string;
    export = _; // changed this
}

我现在可以了

import * as template from './myTemplate.html';

$routeProvider.when("/test", {
    template: template, // Great success!
    controller: MyController,
    controllerAs: "$ctrl"
});

它有效,但为什么 import template from './myTemplate.html'; 无效? 我做错了什么,因为 GitHub 问题中的其他人似乎是这样工作的。

最佳答案

你没有做错任何事情,为了使用 import template from './myTemplate.html'; 你需要使用 export default 语法。

因为 webpack 是处理 html 的那个,所以导入它 doesn't do默认导出默认值。

但是你可以configure您的 html-loader 使用导出默认值。

关于angularjs - 在 typescript 中导入html模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47712892/

相关文章:

javascript - AngularJS UI-路由器 : Two way binding between resolved object in child/parent state—Child state won't update

angular - 类型 ClassB 中的属性 x 不可分配给基类型 ClassA 中的相同属性

javascript - 如何在复选框内显示数组元素 - ionic

javascript - 使用 Angular 路由 url 格式 #!/issue

angular - 在 Angular 的嵌套路由器导出中动态加载模块

node.js - Jade 无法使用 ng-view 指令正确渲染元素

web-applications - 当用户离开页面时如何取消angularjs $timeout

Angular:通过链接参数数组传递路由数据

javascript - Angularjs ng-model 未绑定(bind)到隐藏输入

reactjs - 如何在 typescript 中使用useEffect和forwardRef?