Custom webpack config in angular esbuild

1k Views Asked by At

Currently my Angular project uses a custom webpack configuration file.

          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "allowedCommonJsDependencies": [
                ...
            ],
            "customWebpackConfig": {
              "path": "./angular-webpack.config.js",
              "mergeRules": {
                "module": {
                  "rules": "prepend"
                }
              }
            },

And inside my custom configuration I am using some custom environment variables from mt build.
But I want to move over to esbuild, but the issue is that I can't find any good/obvious way to have some custom esbuild config for Angular.

let DefinePlugin = require('webpack/lib/DefinePlugin');
let OS = require('os');

module.exports = {
    plugins: [
        new DefinePlugin({
            VERSION: JSON.stringify(process.env.VERSION || OS.hostname()),
            URL: JSON.stringify(process.env.URL || ''),
        }),
    ],
}

Any help or tips are appreciated of how I should go about implementing custom defined environment variables for Angular esbuild.

Thank you.

1

There are 1 best solutions below

1
On

At the moment (Angular 17.1), esbuild-based Angular builders do not officially support changes to esbuild and Vite configs, which, if available, would enable passing environment variables to the built application.

As a workaround, you could use obscure executeDevServerBuilder and createBuilder APIs to wrap the default builders and inject esbuild plugins into the fourth argument of executeDevServerBuilder, like esbuild-plugin-define:

const { executeDevServerBuilder } = require("@angular-devkit/build-angular");
const { createBuilder } = require("@angular-devkit/architect");
const { definePlugin } = require('esbuild-plugin-define')

const builder = function (options, context) {
  return executeDevServerBuilder(options, context, undefined, {
    buildPlugins: [definePlugin({
        process: {
          env: {
            BUILD_TIMESTAMP: process.env.BUILD_TIMESTAMP,
          },
        },
      })]
  });
};
module.exports = createBuilder(builder);

Here's an article that explains the process of wrapping a builder in more detail.

Fortunately, you don't have to make your own wrapper, the dot-env package does exactly that.