How to hash AngularJS template htmls with webpack

I recently made the transition from using gulp to webpack for our AngularJS application. While in the gulp version, I utilized the rev plugin to hash all files (css, js, and html), I am facing difficulty adding a hash to the html templates in webpack. This issue is causing problems as the browser keeps serving old html files. How can this be resolved? Below is my webpack configuration file:

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
...

};

if (RemoteServer) {
     console.log('running with remote server', RemoteServer);
     config.devServer.proxy = {
    '/occm/*': 'http://' + RemoteServer
    };
 }

if (isProduction) {
config.plugins.push(
    new CleanWebpackPlugin(buildPath)
    );
}

module.exports = config;

Answer №1

One major advantage of utilizing Webpack is the ability to decrease the number of requests required for a browser to render your application, resulting in faster app initialization. This is accomplished by grouping related resources into "chunks", which are then loaded together in a single request. It's considered inefficient to load individual HTML templates separately without a specific reason.

A best practice approach involves consolidating all JS, HTML, and CSS code into a single large bundle that is loaded once. For larger applications, having a secondary 'vendor' bundle specifically for node_modules code can expedite development since this chunk tends to be more stable.

Another option:

In your scenario, if there isn't a specific need for keeping components separate (which you didn't mention), I would suggest combining HTML with the corresponding control code into a single chunk instead of loading HTML files individually.

An effective starting point would be to generate just two chunks. Update your optimization configuration with the following code:

optimization: {
  splitChunks: {
    cacheGroups: {
      commons: {
        test: /[\\/]node_modules[\\/]/,
        name: 'vendor',
        chunks: 'all'
      }
    }
  }
},

This setup will generate two chunks: a primary chunk containing all JS and HTML files, and a distinct one dedicated solely to content from the node_modules directory.

By doing this, you eliminate concerns about browser caching for HTML files as they are included in your primary chunk, leading to faster app startup times as an added benefit.

Answer №2

When I undertook a similar migration a few years ago, I approached it differently and did not require that particular type of solution. Instead, I focused on encapsulating each component as a module and then optimizing for lazy loading.

// Webpack Configuration
{
  test: /\.html$/,
  use: ['html-loader'],
},

Within each component, I simply included styles and templates like this:

require('./_proposal-page.scss');

(function() {
  'use strict';
  angular.module('component.myComponent', []).component('myComponent', {
    template: require('./proposal-page.html'),
    controller: MyController,
  });

  /** @ngInject */
  function MyController($log) {
    const $ctrl = this;
    $ctrl.$onInit = function() {
      $log.log('$onInit myComponent');
    }
  }
})();
if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports) {
  module.exports = 'component.myComponent';
}

Webpack recognizes the requires and exports each .html file as a module, resulting in smooth functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When access to Ajax .responseText in an alert it can be displayed, however it cannot be stored in a variable or

var response_var=""; // Added for debugging purposes ajax.onreadystatechange = function() { if (ajax.readyState == 4 & ajax.status == 200) { response_var = ajax.responseText; alert(ajax.responseText); // This alerts properly (some text ...

Guide on incorporating a Bootstrap date time picker in an MVC view

Is there a live example available that demonstrates how to implement the latest Bootstrap date time picker in an MVC view? In my project, I have already included: - jQuery. - Bootstrap JS. - Bootstrap CSS. ...

Identify the URL being requested in an AJAX call

Recently, I implemented a function to detect ajax calls. Here is the code snippet: var oldXHR = window.XMLHttpRequest; function newXHR() { var realXHR = new oldXHR(); realXHR.addEventListener("readystatechange", function() { if(realXHR.re ...

Is there anyone who can assist me with the problem I'm facing where Javascript post call is sending a null value to my mongoDB

As a beginner in JS, NodeJS, and MongoDB, I decided to create a quiz website to sharpen my coding skills. However, I have encountered an issue while trying to send the username (string) and total marks (int) to MongoDB using the Post method. Surprisingly, ...

Elements are not detected after applying display:none

Within the onLoad event, I implemented a function to hide multiple div elements by setting their CSS property display to "none" and assigning them the class name "invisible": function hideContent() { laElements = document.getElementById("content").chil ...

Creating a catchy hook for implementing a "Load More" button using JSON data retrieval

How can I implement the functionality for my load more button to fetch and display additional Json data from a fake api? Currently, everything is working as expected except for the load more feature. I have an empty function that needs to be filled in. T ...

Error: The sort method cannot be applied to oResults as it is not a

I encountered this issue. $.ajax({ url: '${searchPatientFileURL}', data: data, success: function(oResults) { console.log("Results:...->"+oResults); oResults.sort(function ...

Showcasing interactive column titles by employing angularjs in an html table

After preparing my data, I aim to showcase it in an HTML table. However, a complication arises each time the $http service is called as it returns a varying number of columns (n). Essentially, I wish to have the first row of the data serve as column names, ...

Navigating with React Links in the wrong context is not possible

Currently in the process of setting up react-router, I have encountered an error stating Uncaught Error: <Link>s rendered outside of a router context cannot navigate.. Despite scouring through various resources on Github and here, none of the solutio ...

Setting up anchor tags with dynamically changing href values does not trigger a get request

I seem to be facing an issue that I can't quite pinpoint. Essentially, I am retrieving data from my database to populate an HTML page and dynamically assigning href values to some anchor tags. However, upon clicking on the links, the page simply reloa ...

Best Practices for Managing Asynchronous Updates in Angular Controllers

Let me explain my current setup -- I have a controller that utilizes a service to perform some tasks and then fetches data asynchronously. Right now, the data is returned after a timeout, but ideally it would involve more complex operations: This is how m ...

What is the best approach to handling this situation in React?

I'm currently developing a React application where the user must select a specific character: comma (,) semicolon (;) colon (:) Other If the user selects 'Other,' a new input field appears, allowing the user to input a custom character. A ...

Class does not have the capability to deserialize an array

I encountered this issue with my code (see image): https://i.sstatic.net/QxI0f.png Here is the snippet of my code: function CheckLoginData() { var user = []; user.Email = $("#tbEmail").val(); user.Password = $("#tbPassword").val(); $.ajax({ type ...

html interactive/expandable tree

I've come across this code which generates an HTML tree, but I'm facing an issue where the tree expands every time I refresh the page. What I want to achieve is to have certain branches expanded and others collapsed when the page is opened, depe ...

Tips for managing large amounts of data retrieval from an API

As a beginner, I am attempting to retrieve data from an API and display it using the v-for directive. However, this process is causing my app to lag. It freezes when new data is fetched or when I search within the list. The following code snippet shows whe ...

The feature to "Highlight text on the page" in React-pdf is currently malfunctioning

I am currently working on incorporating the pdf highlighting feature from React-pdf: import React, { useMemo, useState } from 'react'; // import { Document, Page } from 'react-pdf'; import { Document, Page } from 'react-pdf/dist ...

How to position an image on top of each printed page using HTML/CSS (SCSS)

I've created a simple and small webpage that looks like this: https://i.sstatic.net/R7Ajz.png Everything is perfect in the browser, with all the styles (margin, padding, etc.) just as I want it. However, my issue lies in the print view of the page. ...

Create a dynamic table using an array in jQuery

Currently, my goal is to generate a table using an array with the following format: [ { header: 'ID', values: [1, 2] }, { header: 'First Name', values: ['John', 'Jayne'] }, { header: &ap ...

Executing "mounted" in VueJS SSR with Quasar: A step-by-step guide

In accordance with the documentation: Given that there are no dynamic updates, only beforeCreate and created Vue lifecycle hooks will be triggered during SSR. This implies that any code within other lifecycle hooks like beforeMount or mounted will sole ...

How can I incorporate multiple graphs into my AmCharts display?

I am new to using amcharts and have successfully implemented a code snippet to generate two graphs in a chart. The charts are loaded from an external data source specified in the code. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "d ...