runtime-env / import-meta-env

Build once, deploy anywhere.
http://import-meta-env.org/
MIT License
243 stars 15 forks source link

Compile-time transform not working with an esBuild enabled Angular project #1247

Open jcchalte opened 8 months ago

jcchalte commented 8 months ago

Hello,

tldr;

On a new Angular 17 project with esbuild compilation pipeline (the default one) with import-meta-env configured with a compile-time transformMode, executing the command env DEBUG_IMPORT_META_ENV="true" NAME="Toto" ng build should inject Toto inside the output javascript Angular file, but the output file still contains the non-transformed code :

var _AppComponent = class _AppComponent {
  constructor() {
    this.title = import.meta.env.NAME;
  }
};

some more details

Since Angular 17, esbuild has been added as a choice for the compilation pipeline . Webpack can still be used but esbuild is now the default choice for new angular apps. When import-meta-env is added to an esbuild project, it seems that compile-time transforms are not executed anymore.

When enabling verbose logs (by setting the DEBUG_IMPORT_META_ENV to anything), the output of the ng build command shows that import-meta-env is loaded, but the transform function is not called at all.

image

A little bit of debugging seems to indicate that the issue comes from the fact that build2.onLoad is not called in unplugin, therefore not triggering any transform.

As stated in the ESbuild doc, the onload is only executed if no other plugin handle it

all onLoad callbacks from all plugins will be run in the order they were registered until one takes responsibility for loading the module.

I suspect that Angular register his own plugin, preventing the unplugin one to be called.

Here is a github repository that reproduce this issue : https://github.com/jcchalte/runtime-meta-env-esbuild-bug

Since the ESBuild is quite new, there are not that much configuration examples available online. It could be a simple configuration error on my side. To reproduce this issue, I had to :

this last file has the following content (insipred by your documentation and the @angular-builders/custom-esbuild one) :

import type { Plugin } from 'esbuild';
import * as importMetaEnv from "@import-meta-env/unplugin";

const plugin : Plugin = importMetaEnv.esbuild({
  example:'.env.example',
  transformMode:'compile-time'
});

export default plugin;
jcchalte commented 8 months ago

Oh and by the way, once I find a way to use your library in an angular 17 with esbuild enabled, I will make a PR here with an updated angular sample.