angularangular-unit-test

How use esbuild instead of webpack for unit tests


I have an application, which was generated with Angular CLI v19 and uses the application builder. The application builds and works perfectly fine, however when running ng test, I get a new error:

Error: Should not import the named export 'version' (imported as 'version') from default-exporting module (only default export is available soon).

I narrowed down the error to this piece of code:

import { version } from '../../package.json';

After some investigation, I found this question. It suggested some tweaks to the tsconfig.json which didn't resolve the error. However it made me realize that the error comes from webpack. Which is unexpected for me as I was under the impression that with the application builder I am no longer using webpack.

I want to use esbuild for both the production build and the unit tests, and get rid of webpack completely. How can I achieve this? I searched but didn't find anything about this in the official docs.


Solution

  • If you are using the @angular-devkit/build-angular:karma builder, by default the browser builder is used for building your tests, which uses webpack under the hood.

    Quick fix

    To change this, you can use the builderMode builder option in your angular.json:

    {
      "projects": {
        "my-project": {
          "architect": {
            // ...
            "test": {
              "builder": "@angular-devkit/build-angular:karma",
              "options": {
                "builderMode": "detect"
                // other options
              }
            }
          }
        }
      }
    }
    

    According to the JSON schema, there are three possible values:

    So, in order to get rid of webpack, use application or detect.

    The builderMode option is currently in developer preview and might change before becoming stable.

    Proper Solution

    To properly fix the issue, follow these steps:

    1. Replace the @angular-devkit/build-angular dependency in your package.json with the @angular/build dependency
    2. Run npm install
    3. Go to your angular.json and replace usages of @angular-devkit/build-angular with @angular/build
    4. If you have a karma.conf.js:
      1. Remove "@angular-devkit/build-angular" from the frameworks array
      2. Remove require("@angular-devkit/build-angular/plugins/karma"), from the plugins array.

    Now verify if the setup is working by running ng test.

    A positive side effect of this solution that webpack-related dependencies are removed from your project.