简体   繁体   English

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

[英]Angular 9 How to import HTML file as a string with TypeScript?

I'm using Angular 9.1.3 and Typescript 3.8.3.我正在使用 Angular 9.1.3 和 Typescript 3.8.3。

I want to import html file as a raw string.我想将 html 文件作为原始字符串导入。

For the case:对于这种情况:

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

I'm getting error:我收到错误:

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";

If I add html.d.ts file:如果我添加html.d.ts文件:

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

I'm getting error:我收到错误:

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)">

I had the same problem and I fixed it using the html template inside a typescript file.我遇到了同样的问题,我使用 typescript 文件中的 html 模板修复了它。

You could create a template.ts file like this:您可以像这样创建一个 template.ts 文件:

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

export default template;

And you could simply import the file in this way:您可以简单地以这种方式导入文件:

import template from "./template";

As mention @htn in the comment - will need raw-loader webpack for this.正如评论中提到的@htn - 为此需要 raw-loader webpack。

npm i -D @angular-builders/custom-webpack
npm i -D raw-loader

Update angular.json更新 angular.json

"architect": {
    "build": {
        "builder": "@angular-builders/custom-webpack:browser",
        "options": {
            "customWebpackConfig": {
                "path": "./webpack.config.js"
            },
            ...
        }
    }
}
...

"serve": {
    "builder": "@angular-builders/custom-webpack:dev-server",
    "options": {
        "customWebpackConfig": {
            "path": "./webpack.config.js"
        },
        "browserTarget": "okwiki:build",
        ...
    }
}
...

Add html.d.ts :添加html.d.ts

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

And it works:它有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM