Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Webpack with Angular + templateCache?

I'm learning Webpack. I made an App with Angular and I use templateCache to generate all my html views in one js file than require in App. It works cool. But then the Webpack job:

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"),

That was the part of my webpack config. As the result I get directory "dist" with "bundle.js" && "vendor.bundle.js" and index.html. After that I start server and my App says that it can't GET views. Why? :( As I understand all my views have to be bundled and should be available in the "dist" directory.

like image 861
Imafost Avatar asked Oct 23 '15 10:10

Imafost


2 Answers

I do not use the templateCache at all. Since Angular directives also accept a template as string, I just require() the template with the 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"] }
        ]
    }
}
like image 96
Johannes Ewald Avatar answered Nov 09 '22 11:11

Johannes Ewald


Its late but might as well share this. If you really want to use html fragments maybe for

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

here is how I made it work

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);
    })

});
like image 11
janbee Avatar answered Nov 09 '22 11:11

janbee