Skip to content

Hot Module Replacement (HMR) Problems with Module "NodeNext" #60795

Closed

Description

@DeusProx

Which @angular/* package(s) are the source of the bug?

Don't known / other

Is this a regression?

No

Description

Hot Module Replacement (HMR) Problems with Module "NodeNext"

Setting "module" to "NodeNext" in tsconfig.json leads to errors during HMR, when changing the template or styles of a component.
This repository is showcasing this behaviour by providing two npm scripts esnext and nodenext.

To understand the problem further you can checkout following explanation:

Example

TS:

@Component({
  selector: 'app-root',
  template: `<div class='title'>{{title}}</div>`,
  styles: '.title { font-size: xxx-large }',
})
export class AppComponent {
  title = 'hello world'
}

Running npm run esnext will start the dev server with module set to Esnext and moduleResolution set to bundler.
When now for example changing font-size to x-large will trigger an update, the build will be rerun,
a network request to http://localhost:4200/@ng/component?c=src%2Fcomponent.ts%40AppComponent&t=<timestamp will be made,
following code will be loaded and thus replaces the component with the update correctly.

export default function AppComponent_UpdateMetadata(AppComponent, ɵɵnamespaces) {
    const ɵhmr0 = ɵɵnamespaces[0];
    AppComponent.ɵfac = function AppComponent_Factory(__ngFactoryType__) {
        return new (__ngFactoryType__ || AppComponent)();
    }
    ;
    AppComponent.ɵcmp = /*@__PURE__*/
    ɵhmr0.ɵɵdefineComponent({
        type: AppComponent,
        selectors: [["app-root"]],
        decls: 2,
        vars: 1,
        consts: [[1, "title"]],
        template: function AppComponent_Template(rf, ctx) {
            if (rf & 1) {
                ɵhmr0.ɵɵelementStart(0, "div", 0);
                ɵhmr0.ɵɵtext(1);
                ɵhmr0.ɵɵelementEnd();
            }
            if (rf & 2) {
                ɵhmr0.ɵɵadvance();
                ɵhmr0.ɵɵtextInterpolate(ctx.title);
            }
        },
        styles: ["\n\n.title[_ngcontent-%COMP%] {\n  font-size: x-large;\n}\n/*# sourceMappingURL=component.css.map */"]
    });
    (() => {
        (typeof ngDevMode === "undefined" || ngDevMode) && ɵhmr0.ɵsetClassDebugInfo(AppComponent, {
            className: "AppComponent",
            filePath: "src/component.ts",
            lineNumber: 8
        });
    })();
}

Running npm run nodenext instead will start the dev server with module set to NodeNext.
When doing the same change the network request will instead deliver following code:

"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.default = AppComponent_UpdateMetadata;
function AppComponent_UpdateMetadata(AppComponent, ɵɵnamespaces) {
    const ɵhmr0 = ɵɵnamespaces[0];
    AppComponent.ɵfac = function AppComponent_Factory(__ngFactoryType__) {
        return new (__ngFactoryType__ || AppComponent)();
    };
    AppComponent.ɵcmp = /*@__PURE__*/
    ɵhmr0.ɵɵdefineComponent({
        type: AppComponent,
        selectors: [["app-root"]],
        decls: 2,
        vars: 1,
        consts: [[1, "title"]],
        template: function AppComponent_Template(rf, ctx) {
            if (rf & 1) {
                ɵhmr0.ɵɵelementStart(0, "div", 0);
                ɵhmr0.ɵɵtext(1);
                ɵhmr0.ɵɵelementEnd();
            }
            if (rf & 2) {
                ɵhmr0.ɵɵadvance();
                ɵhmr0.ɵɵtextInterpolate(ctx.title);
            }
        },
        styles: ["\n\n.title[_ngcontent-%COMP%] {\n  font-size: x-large;\n}\n/*# sourceMappingURL=component.css.map */"]
    });
    (() => {
        (typeof ngDevMode === "undefined" || ngDevMode) && ɵhmr0.ɵsetClassDebugInfo(AppComponent, {
            className: "AppComponent",
            filePath: "src/component.ts",
            lineNumber: 8
        });
    })();
}

This code will throw following error:

zone.js:2317 ReferenceError: exports is not defined
    at component?c=src%2Fco…=1744143776918:2:23

Please provide a link to a minimal reproduction of the bug

https://github.com/DeusProx/hmr-nodenext

Please provide the exception or error you saw

zone.js:2317 ReferenceError: exports is not defined
at component?c=src%2Fco…=1744143776918:2:23

Please provide the environment you discovered this bug in (run ng version)

% ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 19.2.6
Node: 20.15.1
Package Manager: npm 10.9.2
OS: linux x64

Angular: 19.2.5
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1902.6
@angular-devkit/build-angular   19.2.6
@angular-devkit/core            19.2.6
@angular-devkit/schematics      19.2.6
@angular/cli                    19.2.6
@schematics/angular             19.2.6
rxjs                            7.8.2
typescript                      5.8.3
zone.js                         0.15.0

Anything else?

Additional problems with Module "NodeNext"

Additionally to the HMR problem the setting also seems to break the angular LSP for templates.
The local LSP of your Editor will load the tsconfig.json so make sure to adjust it accordingly.

Activity

  1. self-assigned this
    on Apr 9, 2025
  2. added a commit that references this issue on Apr 9, 2025
    8f235b4
  3. alan-agius4 commented on Apr 9, 2025

    @alan-agius4
    Contributor

    Out of curiosity, why are you using NodeNext in a web application? This typically results in CommonJS output, which isn’t optimized for the web and can unnecessarily inflate your bundle size.

  4. DeusProx commented on Apr 9, 2025

    @DeusProx
    Author

    @alan-agius4

    In my opinion using esnext and bundler is the right way to bundle an angular application in general, but a collegue of mine had the task to migrate a lot of projects to ESM and NodeNext was choosen since it supports conditional exports, subpath exports and especially forces to use suffixes (.js) in imports. This improved other parts as this angular project is just included as a webcomponent at other places.

    We just found out after this switch that it broke HMR and LSP in this part of the project and reverted for now until further feedback.

  5. kayahr commented on Apr 9, 2025

    @kayahr

    NodeNext typically does NOT result in CommonJS output. TypeScript itself generates ESM output when module resolution is set to NodeNext und package.json is set to type module.

    NodeNext module resolution is necessary to use dependencies which use modern exports (conditional exports, sub-path exports). They can't be imported by TypeScript when using ESNext.

  6. alan-agius4 commented on Apr 9, 2025

    @alan-agius4
    Contributor

    There seems to be some confusion between the module and moduleResolution options.

    The module option defines the output module format, while moduleResolution controls how modules are resolved. In most bundled applications, it's recommended to use module: preserve, which automatically enables moduleResolution: bundler. This setup differs from module: NodeNext, which requires explicit file extensions due to the Node.js runtime's behavior.

    With modern export patterns, setting module to NodeNext isn't strictly necessary. The behavior you're observing where conditional exports work with module: NodeNext is actually due to the fact that this setting also switches moduleResolution to NodeNext. So, it's the moduleResolution that drives this functionality, and similar results can be achieved using moduleResolution: bundler or module: preserve without the hard requirement to include file extensions.

    From TypeScript documentation

    A common misconception is that node16—nodenext only emit ES modules. In reality, these modes describe versions of Node.js that support ES modules, not just projects that use ES modules. Both ESM and CommonJS emit are supported, based on the detected module format of each file. Because they are the only module options that reflect the complexities of Node.js’s dual module system, they are the only correct module options for all apps and libraries that are intended to run in Node.js v12 or later, whether they use ES modules or not.

    TL;DR: Unless you are developing an unbundled Node.js application or library, setting module to NodeXX is not ideal, as it conflicts with the intention to create a bundled web app and can lead to CommonJS output in cases where TypeScript does not detect the input module as ESM.

  7. added a commit that references this issue on Apr 9, 2025
    fc946c5
  8. added a commit that references this issue on Apr 9, 2025
    8744c9a
  9. DeusProx commented on Apr 10, 2025

    @DeusProx
    Author

    Thanks for the input and fast fix everyone!

  10. angular-automatic-lock-bot commented on May 11, 2025

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  11. locked and limited conversation to collaborators on May 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions