javascript - Angular 9 如何使用 TypeScript 将 HTML 文件导入为字符串?

标签 javascript angular typescript

我正在使用 Angular 9.1.3 和 Typescript 3.8.3。

我想将 html 文件作为原始字符串导入。

案例:

import * as template from "./projects.page.html";
console.log("Template: ", template);

我收到错误:

ERROR in src/app/features/projects/projects.page.ts:41:27 - error TS2307: Cannot find module './projects.page.html'.

41 import * as template from "./projects.page.html";

如果我添加 html.d.ts 文件:

declare module "*.html" {
    const content: string;
    export default content;
}

我遇到错误:

ERROR in ./src/app/features/projects/projects.page.html 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> <div style="height: calc(100vh - 64px)">

最佳答案

我遇到了同样的问题,我使用 typescript 文件中的 html 模板修复了它。

您可以像这样创建一个 template.ts 文件:

const template = `
  <div> Your template here! </div> 
`;

export default template;

你可以简单地以这种方式导入文件:

import template from "./template";

关于javascript - Angular 9 如何使用 TypeScript 将 HTML 文件导入为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62165638/

相关文章:

Javascript删除字符串中的所有 '|'

javascript - 通过单击堆叠的条形图打开选项卡

javascript - HTML 实体到 Unicode 转义序列

javascript - 获取基本 href Angular 4

angular - Observable 在 redux 的状态改变后没有更新

javascript - 过滤数组并查找拼接索引

javascript - 有没有办法通过链接变量名来访问 typescript 中的子对象

javascript - 鼠标悬停在 DOM 元素上时检测按键事件

Angular 2 @Output 参数

javascript - "Workspace needs to be loaded before it is used"on ng new