Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to load AngularJS templates for Webpack 4?

So far I've been able to bundle up all our controllers/directives/services into 1 script and I also bundled all the vendor scripts into another script file. Now I'm having trouble figuring out what the right way to load the AngularJS template files are. We are currently using Grunt and just copying the exact folder structure over to the dist folder but clearly this won't work in Webpack. Here is an example of our project structure(from the John Papa style guide)

enter image description here

My project inside the dist folder is currently rendered as follows:

enter image description here

Anybody have any input?

like image 400
Jack Johnson Avatar asked Dec 17 '22 16:12

Jack Johnson


1 Answers

AngularJS templates are html files, so you need to add some loader for handling them.

  1. You have multiple options, bundle those html files into the js bundle, using html-loader, pros of this approach is that your app won't make ajax call for the template, cons, your js bundle size will become large. This will allow you to "require" your html template inside your controllers.

  2. copy those raw files using copy-webpack-plugin, this way it will work the same way it works with Grunt (providing templateUrl path to the file that was copied).

  3. In-order to be specific regarding lazy-loaded files you can attach .lazy.html suffix. Then, enable file-loader on the .lazy.html files & assign it to templateUrl, and the regular once use with template: require('template.html').

As of best practice, I would "require" critical templates so they will be in the js bundle, and lazy load (via templateUrl) non-critical ones.

This is an example of webpack.config.js file:

module.exports = {
  module: {
    rules: [
      {
        test: /\.lazy\.html$/,
        use: [
          {
            loader: 'file-loader',
            options: {},
          },
        ],
      },
      {
        test: /\.html$/,
        exclude: /\.lazy\.html$/
        use: [
          {
            loader: 'html-loader',
            options: {
              minimize: true,
            },
          },
        ],
      },
    ],
  },
};
// critical.component.js
angular.
  module('myApp').
  component('greetUser', {
    template: require('critical.html'),
    controller: function GreetUserController() {
      this.user = 'world';
    }
  });


// none-critical.component.js

angular.
  module('myApp').
  component('greetUser', {
    templateUrl: require('non-critical.lazy.html'),
    controller: function GreetUserController() {
      this.user = 'world';
    }
  });
like image 92
felixmosh Avatar answered Feb 14 '23 01:02

felixmosh