webpack-dev-server provides support for serving previous versions of the bundle

I have encountered a strange issue while using Webpack to build an Angular 2 AOT app (see configuration below). When I run webpack, everything runs smoothly. However, when I switch to using the webpack-dev-server, I face a peculiar problem. The first page load works fine, but subsequent loads always display the previous version of the bundle.

Just to illustrate, if I start the server with an Angular component template containing <h1>hello</h1>, I see "hello" as expected. But when I update the template to <h1>hello world</h1>, the page reloads but still shows "hello" (with the console message [WDS] Nothing changed). Then, if I modify the template once more to

<h1>goodbye world</h1>
, the page reloads displaying "hello world," reflecting the change made on the prior reload.

This anomaly only occurs with TypeScript files and Angular templates that are compiled into TypeScript files – not with the index.html file (despite employing html-webpack-plugin). Additionally, the delay is absent when using webpack --watch, happening solely with webpack-dev-server.

The provided webpack.config.js:

const webpack = require("webpack");
const ngToolsWebpack = require("@ngtools/webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: {
        app: "./src/main.ts",
        vendor: ["@angular/core", "@angular/common", "@angular/platform-browser"],
        polyfill: ["zone.js/dist/zone.js"],
    },
    output: {
        path: __dirname + "/dist",
        filename: "[name].js",
    },

    resolve: {
        extensions: [".ts", ".js"],
    },

    module: {
        rules: [
            { test: /\.html$/, use: "raw-loader" },
            { test: /\.css$/, use: "raw-loader" },
            { test: /\.ts$/, use: "@ngtools/webpack" },
        ],
    },

    plugins: [
        new ngToolsWebpack.AotPlugin({
            tsConfigPath: "./tsconfig.json",
        }),
        new webpack.optimize.CommonsChunkPlugin({
            names: ["vendor", "polyfill"],
        }),
        new HtmlWebpackPlugin({
            template: "src/index.html",
        }),
    ],
};

Answer №1

Have you considered incorporating the chunkhash property?

const webpack = require("webpack");
const ngToolsWebpack = require("@ngtools/webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: {
        app: "./src/main.ts",
        vendor: ["@angular/core", "@angular/common", "@angular/platform-browser"],
        polyfill: ["zone.js/dist/zone.js"],
    },
    output: {
        path: __dirname + "/dist",
        filename: "[name].[chunkhash].js",
    },

    resolve: {
        extensions: [".ts", ".js"],
    },

    module: {
        rules: [
            { test: /\.html$/, use: "raw-loader" },
            { test: /\.css$/, use: "raw-loader" },
            { test: /\.ts$/, use: "@ngtools/webpack" },
        ],
    },

    plugins: [
        new ngToolsWebpack.AotPlugin({
            tsConfigPath: "./tsconfig.json",
        }),
        new webpack.optimize.CommonsChunkPlugin({
            names: ["vendor", "polyfill", "manifest"],
        }),
        new HtmlWebpackPlugin({
            template: "src/index.html",
        }),
    ],
};

Hopefully, this suggestion proves to be useful.

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

Tips for handling TypeError when testing formgroups in Angular unit tests---How to address TypeError

While attempting to conduct unit testing on my form fields in Angular, I encountered an issue with Karma stating that my property is undefined. When I logged the formGroup, it returned as undefined. However, upon logging my component, all parameters were r ...

Overloading TypeScript functions with Observable<T | T[]>

Looking for some guidance from the experts: Is there a way to simplify the function overload in the example below by removing as Observable<string[]> and using T and T[] instead? Here's a basic example to illustrate: import { Observable } from ...

Having trouble with your Ionic 2 Android release build getting stuck on a white screen post-splash screen?

Several weeks ago, I posted a question regarding this issue but unfortunately did not receive any response. So here I am posting again with a more specific problem. The Problem: 1.) I execute: $ ionic cordova build android --release --prod 2.) Then ...

Discovering the IP address of Azure Functions

Is there a way to retrieve the IP address of an Azure function? I am looking for a method to make a request to the function and receive its IP address in return. I attempted the following code, but it hung indefinitely without generating any results: imp ...

Top method for transferring information from a service to a dynamic format in Angular5

Looking for the most efficient method to populate a form with data from a service in Angular 5. My goal is to keep component code to a minimum and have the variable-data stored within services rather than components. The content is loaded through a second ...

Conditionally using TypeScript, learn the process of implementing useQuery within React-Query

I am currently utilizing useQuery provided by the react-query library to fetch specific data only under certain conditions. How can I implement this feature? Below is an example of how I am using useQuery: const query = useQuery<APIResponse, Error&g ...

Learn the best way to retrieve the highest number from a Array<String> in TypeScript or JavaScript

Can someone help me create a function in JS or TS that meets the following requirements? I am looking for a functional programming approach. ・Input type: Array(String) ・Output type: string or undefined Examples Input Result ["" ...

Mastering the Proper Use of Bootstrap-Tagsinput in Angular2

I have been trying to incorporate the bootstrap-tagsinput library into my Angular2 project. I successfully installed the library using the package.json file: "dependencies": { ... "bootstrap-tagsinput": "^0.7.1", ... } After installation, ...

How can Angular help optimize an array by implementing specific conditions for reduction?

In my database, I have an ordered array that looks like this: let data = [ {month: 1, visible: true}, {month: 2, visible: false}, {month: 3, visible: true}, {month: 4, visible: false}, {month: 5, visibl ...

"Error: The term 'Readable' is not

When I input this code: const { Readable } = require('stream'); Readable ends up being undefined. However, when I try this code instead: import { Readable } from 'stream'; Readable becomes an empty object with no properties. It&apos ...

I need guidance on retrieving items from the useRouter() hook when utilizing Next.js with the App Router approach

This code snippet demonstrates how to use Pages Router in React import { useRouter } from "next/router"; import React from "react"; function ShowroomListings({}) { const router = useRouter(); const { listingId } = router.query as ...

Losing focus after typing just one letter

Having issues with a component containing multiple inputs; every time I try to type in one of the fields, it triggers a re-render and causes the input field to lose focus. export default function EventModal({ data, show, setShown }: Props) { const [sav ...

Encountering a surprise focus error in ngui-auto-complete within Angular

In the process of developing a web application, I have encountered an unexpected focus issue with the ngui-auto-complete on one of the pages. Despite not setting any focus event for this particular element, it remains focused once the content is initialize ...

If "return object[value1][value2] || default" does not work, it means that value1 is not a recognized property

Within my code, there is an object literal containing a method that retrieves a sub-property based on a specific input. If the lookup fails, it should return a default property. //private class, no export class TemplateSelection { 'bills'; & ...

Webpack is attempting to include an excessive amount of modules while utilizing knex.js with AWS Amplify

I'm running into build errors with a next.js application on AWS Amplify, even though it builds and runs smoothly on my local machine. The issue seems to be related to webpack trying to include all SQL packages that knex may use. The specific error mes ...

What is the method for transmitting a URL API from an ASP.NET Core server to my Angular 2 single application?

Is there a way to securely share the url of the web api, which is hosted on a different server with a different domain, from my asp net core server to my client angular2? Currently, I am storing my settings in a typescript config file within my angular2 ap ...

Best approach for managing Angular dependencies: Is it acceptable to link to a TypeScript file other than its corresponding component.ts in a component.html file?

My friend and I recently had a disagreement about a file in our project called experiment-row.component.html. The code in question looked like this: *ngIf="experimentsPageService.isRegularStatusIconVisible(experiment)" I argued that it is not go ...

What is the best way to create a highlighted navigation bar using Angular 2?

Is there a way to keep the navbar active even after refreshing the page in Angular 2? I am currently using CSS to accomplish this, but the active tab is removed upon page refresh. Any suggestions on how to tackle this? HTML:-- <ul class="nav navbar- ...

Angular component communication issue - emitter malfunctioning

Angular 4 Event emitter not functioning as expected despite following a tutorial for implementation. I am open to alternative solutions if available. Here is the code snippet for the transmitter component: .HTML <nav class="navbar navbar-toggleable-m ...

Angular is unable to bind to 'dirUnless' because it is not recognized as a valid property

I am seeking to implement a custom directive that acts as the opposite of *ngIf. Below is the code I have written for this custom directive: import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core'; @Directive({ sele ...