【问题标题】:Angular (7) component accepts only html filesAngular (7) 组件只接受 html 文件
【发布时间】:2020-04-16 14:52:56
【问题描述】:

组件定义如下:

import {Component} from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent {

}

我想在某些特定组件中加载扩展名为 htm "app.component.htm" 的文件,而不是 "app.component.html"

@Component({
  selector: 'app-root',
  templateUrl: './app.component.htm',
  styleUrls: ['./app.component.less']
})

由于某种原因它不起作用,它说:

ERROR in ./app.component.htm 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
<p>
  app component works!
</p>
「wdm」: Failed to compile. 

请帮我找到一种加载 htm 文件的方法?我知道有一种方法可以使用 Webpack 进行引导,我想保留 ng-serve\cli angular.json 的当前版本!

谢谢!

【问题讨论】:

  • 请提供完整的ts文件
  • 因为根据angular没有像htm这样的文件所以不支持它只有在你使用angularjs时才有效
  • 是什么迫使您使用 .htm 而不是 .html 文件?
  • 有一个过程可以使用custom builder 生成与现有配置合并的自定义 webpack 配置,允许您为非标准化文件类型指定自定义加载器。但是,我自己从来没有真正做过,所以我不知道你需要什么的确切语法....
  • 还要记住,这似乎在 8.x 中发生了变化,所以它也可能是一个死胡同......

标签: angular angular-cli


【解决方案1】:

将您的 Angular 版本升级到 Angular 8,这是在 Angular 8 中修复的。

@Component({
  selector: 'app-root',
  templateUrl: './app.component.htm',
  styleUrls: ['./app.component.less']
})

【讨论】:

    【解决方案2】:

    可能很难修改角度加载其模板文件的方式,但您可以使用@angular-builders/custom-webpack 结合raw-loaderhtm 文件导入component.ts,而不是在组件配置中使用templateUrl 使用@987654328 @ 并使用导入的值设置它。该解决方案几乎在此 SO question 中进行了描述,并进行了一些更改,它也适用于您:

    1. npm i -D @angular-builders/custom-webpack raw-loader安装需要的包

    2. 如下配置angular.json:

    "build": {
              "builder": "@angular-builders/custom-webpack:browser", // change builder
                "options": {
                    "customWebpackConfig": { // add custom config
                         "path": "./extra-webpack.config.js"
                      }, // keep the rest same
    
    1. extra-webpack.config.js 文件添加到与angular.json 相同的目录中,内容如下:
    module.exports = {
      module: {
        rules: [
          {
            test: /\.htm$/, // this just tells use raw-loader to load *.htm files
            use: 'raw-loader'
          }
        ]
      }
    };
    
    1. typings.d.ts 文件添加到您的src 文件夹中(这将避免打字稿导入错误):
    declare module '*.htm' {
      const value: string;
      export default value;
    }
    
    1. 并在您的组件中使用原始加载程序导入 htm 文件
    import {Component} from '@angular/core';
    
    import str from 'raw-loader!./app.component.htm';
    
    @Component({
      selector: 'app-root',
      template: str, // notice not url just string
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
    }
    

    我已设法在本地运行此配置,但无法使其在 stackblitz 中运行。不工作的 Stackblitz example

    【讨论】:

      猜你喜欢
      • 2014-09-10
      • 2021-05-21
      • 2018-12-19
      • 2013-03-03
      • 1970-01-01
      • 2010-12-05
      • 2019-02-10
      • 2019-10-12
      • 2017-03-30
      相关资源
      最近更新 更多