简体   繁体   中英

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

I'm using Angular 9.1.3 and Typescript 3.8.3.

I want to import html file as a raw string.

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:

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.

You could create a template.ts file like this:

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.

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

Update 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 :

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

And it works:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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