【问题标题】:Use angular template cache with browserify在 browserify 中使用角度模板缓存
【发布时间】:2014-12-17 14:54:31
【问题描述】:

我正在使用 browserify 和 ui-router 构建一个小型 Angular 应用程序。因为我不想使用服务器,所以我想使用 Angular 的 $templateCache 来存储我的所有模板,如下所示:

exports.templateCache = ["$templateCache", function($templateCache) {
  'use strict';

  $templateCache.put('partials/someState.html',
    "myHtmlCode"
  );
}];

为了填充缓存,我使用 grunt 查看我的 partials 文件夹,获取所有 html 并使用 grunt-angular-templates 将其加载到缓存中:

 ngtemplates:  {
  myApp: {
    cwd: 'dist/',
    src: 'partials/**.html',
    dest: 'src/js/templates/templates.js',
    options: {
      bootstrap:  function(module, script) {
        return 'exports.templateCache = ["$templateCache", function($templateCache) {\n' +
          script +
          '}];'
      }
    }
  }
},

然后我使用 browersify 将我所有的 js 组合在一起:

browserify: {
  dist: {
    files: {
      'dist/js/app.js': [
          'src/js/templates/**',
          'src/app.js'
          ],
    }
  }
},

到目前为止这是有效的,但这个工作流程对我来说看起来非常笨拙:我有一个中间步骤,我在 src 目录中创建 templates.js 文件,并且在我的 grunt 文件中有硬编码代码。

有什么方法可以更优雅地做到这一点? browserify 有内置解决方案来解决这个问题吗?

【问题讨论】:

  • 处理类似问题。您找到解决方案了吗?

标签: javascript angularjs caching gruntjs browserify


【解决方案1】:

browserify-ng-html2js 旨在解决此问题。

只需在 package.json 中添加:

"browserify": {
    "transform": ["browserify-ng-html2js"]
 }

你会看到它是否会说话:)

【讨论】:

  • 还有 'ngify' github,另一个 Browserify 转换。 browserify().transform(require('ngify')).bundle()...
  • 这两种转换都将文件名指定为模块名。随着应用的发展,这使得它难以使用。
  • ngify 刚刚更新为允许相对路径
【解决方案2】:

尝试对 browserify 进行转换,让您有可能需要 html 文件(例如 Stringify)。然后你可以 require('yourPartial.html') 作为字符串:

$templateCache.put('yourPartialId', require('./partials/yourPartial.html'));

// html file
<div ng-include=" 'yourPartialId' "></div>    

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2015-09-12
    • 2014-08-21
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2014-09-01
    • 2023-03-30
    相关资源
    最近更新 更多