[AngularJS + Webpack] Requiring Templates

With Angular, most of the time you're specifying a templateUrl for your directives and states/routes. This means you need to make sure that you're loading in these templates into the $templateCache for your tests and production. Oh, and don't forget to update all your URLs whenever you move the files around! When you add in Webpack and the html-loader, you don't need to do this anymore. Simply require the html file and your work is done!

 

Install:

npm install -D html-loader

 

webpack.config.js:

module.exports = {
    entry: {
        app: ['./app/index.js']
    },
    output: {
        path: './build',
        filename: 'bundle.js'
    },
    module: {
        loaders: [
            {test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/},
            {test: /\.html$/, loader: 'html-loader', exclude: /node_modules/}
        ]
    }
};

 

hello.js:

export default (ngModule) => {
    ngModule.directive('hello',  () => {
        return {
            restrict: 'E',
            scope: {},
            template: require('./hello.html'),
            controllerAs: 'vm',
            controller: function() {
                var vm = this;
                vm.greeting = "Hello";
            }
        }
    })
}

 

posted @ 2015-09-08 17:43  Zhentiw  阅读(507)  评论(0编辑  收藏  举报