使用带有browserify的角度模板缓存

Spe*_*her 10 javascript caching angularjs browserify gruntjs

我正在使用browserify构建一个小角度应用程序ui-router.由于我不想使用服务器,我想使用angular $templateCache这样存储我的所有模板:

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

  $templateCache.put('partials/someState.html',
    "myHtmlCode"
  );
}];
Run Code Online (Sandbox Code Playgroud)

要填充缓存,我使用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 +
          '}];'
      }
    }
  }
},
Run Code Online (Sandbox Code Playgroud)

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

browserify: {
  dist: {
    files: {
      'dist/js/app.js': [
          'src/js/templates/**',
          'src/app.js'
          ],
    }
  }
},
Run Code Online (Sandbox Code Playgroud)

这个工作到目前为止,但这个工作流对我来说看起来很笨重:我有一个中间步骤,我templates.js在我的src目录中创建文件,我在我的grunt文件中有硬编码的代码.

有没有办法更优雅地做到这一点?browserify是否附带内置解决方案来解决这个问题?

Jak*_*ski 0

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

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

// html file
<div ng-include=" 'yourPartialId' "></div>    
Run Code Online (Sandbox Code Playgroud)