生产环境下,使用webpack时无法找到Angular的templateUrl。

3

我有一个使用TypeScript编写的Angular 1.5应用程序组件。我使用webpack作为构建工具。我有以下组件 -

import {Component} from "../../common/decorators"

const app = angular.module('app');
 @Component(app, {
  selector: 'navComponent',
  controllerAs: 'ctrl',
  styleUrls: './nav.style.scss',
  templateUrl: './nav.template.html'
 })
 class navComponent {
 static $inject = ['$scope', '$attrs', '$element'];

 constructor(private $element, $scope: ng.IScope, $attrs) { 

 }   
}

装饰器是

export const Component = function(module: ng.IModule, options: {
  selector:string,
  controllerAs?: string,
  styleUrls?: string,
  template?: string,
  templateUrl?: string
}) {
  return (controller: Function) => {
   module.component(options.selector, angular.extend(options, {   controller: controller }));
 }
}

本地机器上运行正常,但在进行webpack打包后,使用bundle.js在生产环境中无法正常工作。

这是我正在使用的加载器。

loaders: [
        {
            test: /\.html$/,
            loader: 'html-loader',
        }

以下是错误信息:

错误: [$compile:tpload] 无法加载模板:/components/nav/nav.template.html (HTTP状态码:404 Not Found)

2个回答

2
您可以尝试嵌入您的模板:
...
template: require('./nav.template.html')
...

如果你想使用单独的模板文件,可以使用CopyWebpackPlugin。但是在部署应用程序时,每个文件都会多出一个请求。


1
谢谢回复。它有效。我想知道为什么URL不起作用?此外,使用webpack处理HTML文件的最佳实践是什么?将其作为单独的调用文件还是放在模块内部? - Jhankar
1
URL无法工作,因为Webpack开发服务器例如不会在“虚拟”目录中创建文件,所以Angular无法获取它。关于最佳实践-无法回答...我更喜欢使用require,Webpack为我的应用程序生成一个大的JS文件。它可以在没有对任何模板HTML的请求的情况下工作,只需从API获取JSON即可。 - Makarov Sergey

0

由于您正在使用ES6模块导入,因此您可以使用以下导入语句样式来导入您的HTML

import mainTemplate from './mainpage.component.html';

然后您可以在组件中按如下方式引用此模板

  export class mainPageComponent implements ng.IComponentOptions {
  public bindings: any;
  public controller: any;
  public template: string;
  public controllerAs: string;


  constructor() {
    this.bindings = {};
    this.template = mainTemplate,
    this.controllerAs = "vm";
    this.controller =mainPageController;
  }
}

现在这会加载你的模板,但为了在 webpack 构建过程中正确处理它(这里使用的是 webpack 3),你可以使用 html-loader

{
    test: /\.html$/,
    exclude: /node_modules/,
    use: { loader: "html-loader" }
  }

这应该能帮到你


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接