如何使用 Webpack 和 Angular + templateCache?

How to use Webpack with Angular + templateCache?

我正在学习 Webpack。我用 Angular 制作了一个应用程序,我使用 templateCache 在一个 js 文件中生成我所有的 html 视图,而不是应用程序中的要求。它很酷。但是 Webpack 作业:

entry: {
    app: ["bootstrap-webpack!./bootstrap.config.js", './app/app.js'],
    vendor: ['angular', 'bootstrap', 'angular-ui-router', 'oclazyload']
},
output: {
    path: path.join(__dirname, "dist"),
    filename: '/bundle.js'
},
plugins: [
    new webpack.optimize.CommonsChunkPlugin(
        /* chunkName= */ "vendor", /* filename= */ "/vendor.bundle.js"),

那是我的 webpack 配置的一部分。结果我得到目录 "dist" 和 "bundle.js" && "vendor.bundle.js" 和 index.html。之后我启动服务器,我的应用程序说它无法获取视图。为什么? :( 据我所知,我所有的观点都必须捆绑在一起,并且应该在 "dist" 目录中可用。

我根本不使用 templateCache。由于 Angular 指令也接受模板作为字符串,我只是 require() 带有 html-loader 的模板。

function MyDirective() {
    return {
        restrict: "E",
        replace: true,
        template: require("./MyDirective.html")
    };
}

// in your webpack.config.js
module.exports = {
    module: {
        loaders: [
            { test: /\.html$/, loaders: ["html"] }
        ]
    }
}

来晚了,但不妨分享一下。如果你真的想使用 html 片段可能

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

下面是我如何让它工作的

var appMod = angular.module('app'); 

appMod.run(function($templateCache) {

    function requireAll(requireContext) {
        return requireContext.keys().map(function(val){
            return {
                // tpl will hold the value of your html string because thanks to wepbpack "raw-loader" **important**
                tpl:requireContext(val),

                //name is just the filename
                name : val.split('/').pop()
            }
        });
    }

    // here "../" is my app folder root
    // tplc is the naming convention of the templates
    let modules = requireAll(require.context("../", true, /\.tplc\.html$/));

    modules.map(function (val) {
        $templateCache.put(val.name, val.tpl);
    })

});