Gulp Angular 构建模板缓存问题

Gulp Angular build templateCache issue

本文关键字:缓存 问题 建模 Angular 构建 Gulp      更新时间:2023-09-26

我的build.js正在使用ngHtml2js将指令中的部分转换为js文件。

gulp.task('partials', function () {
  return gulp.src('src/{components,app}/**/*.html')
    .pipe($.ngHtml2js({
      moduleName: 'testApp'
    }))
    .pipe(gulp.dest('.tmp'))
    .pipe($.size());
});

其中,我的指令位于组件>指令的组件文件夹中。

问题是,当我尝试部署 dist 文件夹时,来自路由 JS 文件的静态部分调用被触发,并且我得到 404。

angular.module(ModuleName)
        .directive('collapseWindow', ['$parse', function (parse) {
            return {
                templateUrl:'/components/directives/collapse.html',
                transclude:true,
                restrict: 'A'

在我的理解中,ngHtml2js 将部分转换为 module.run 块作为

module.run(['$templateCache', function($templateCache) {
  $templateCache.put('components/directives/collapse.html',
    '<div class="collapsible">'n' ...

但是,为什么我会收到404错误,例如

 GET http://localhost:3000/components/directives/collapse.html 404 (Not Found)

解决了。原因是 templateUrl 被赋予了绝对路径(开头带有"/"),但 templateCache 使用相对路径。因此,从模板URL中删除"/"解决了问题

您需要将模板模块作为依赖项添加到 Angular 应用程序模块中。还要确保在应用程序代码之前已在浏览器中加载模板缓存 js 文件。

我为主应用程序添加了此配置。它覆盖了 ngnewroute 的模板映射

.config (function ($componentLoaderProvider) {
  $componentLoaderProvider.setTemplateMapping(function (name) {
    return 'components/' + name + '/' + name + '.html';
  });
})