angular / angular-cli

CLI tool for Angular
https://cli.angular.dev
MIT License
26.79k stars 11.98k forks source link

Feature request: add indexHtmlTransformer and plugins options to application builder #28607

Open zip-fa opened 1 month ago

zip-fa commented 1 month ago

Command

build

Description

Hi. This feature exists for a long time in angular-builders and nx custom builders' code. plugins allows adding vite plugins; we use this option to use custom plugin with .env file parsing, adding ENVIRONMENT_NAME and __APP_VERSION__ global variables and much more. I guess there are plenty of other use-cases for this. indexHtmlTransformer allows to replace some placeholders in index.html while building or serving an app. Useful to make similar DX when building or developing locally my app.

There is not much to do with these two, but i think this will boost DX many times. Thanks for your time!

Describe the solution you'd like

No response

Describe alternatives you've considered

https://github.com/nrwl/nx/blob/master/packages/angular/src/executors/application/application.impl.ts

alan-agius4 commented 1 month ago

@zip-fa, thanks for this feature request.

While we do offer the option to add additional plugins and modify the index.html file, we do not consider this to be part of the "recommended" or optimal path.

What is the use-case of including environment variables directly in the index.html instead of embedding them in the JS bundle and setting them with the --define option?

zip-fa commented 1 month ago

You misunderstood me a bit. NX parses .env.{envName} files automatically and set them inside process.env We have three environments: staging, prod and dev. While it's ok to use --define option, it's much easier to depend on .env files. Our plugin to define global env vars is:

const path = require('path');
const { dirname } = require('node:path');
const envPrefix = /^APP_/i;

function getProjectEnvVars() {
  const envVars = {};

  for (const key in process.env) {
    if (envPrefix.test(key)) {
      envVars[key] = process.env[key];
    }
  }

  return envVars;
}

const envVarPlugin = {
  name: 'env-var-plugin',
  setup(build) {
    const options = build.initialOptions;
    const envVars = getProjectEnvVars();
    const sourceDirectory = dirname(build.initialOptions.tsconfig);
    const packageJsonPath = sourceDirectory + '/package.json';

    options.define['__APP_VERSION__'] = `"${ require(packageJsonPath).version }"`;
    options.define['__SOURCE_DIRECTORY__'] = `"${ sourceDirectory }"`;
    options.define['BUILD_ENV'] = JSON.stringify(envVars);
    options.define['ENVIRONMENT_NAME'] = `"${ process.env.NX_TASK_TARGET_CONFIGURATION }"`;
  }
};

module.exports = envVarPlugin

For index.html we change placeholders on the fly:

<head>
{analytics_scripts}
</head>

transformer:

export default function(indexContent: string) {
  const replacements: Record<string, string> = {
    '{analytics_scripts}': '...'
  };

  for (const key in replacements) {
    indexContent = indexContent.replaceAll(key, replacements[key]);
  }

  return indexContent;
imaksp commented 1 week ago

Hi all, adding another use case, some scripts needs to be added in head section like this:

 <script async src="https://www.googletagmanager.com/gtag/js?id=GTM-XXXX"></script>

currently we can't use variable for GTM id in index.html, we can also load script using js/angular, but it will have some issue if its loaded later from angular app code. sometimes script's domain name can also be different based on env, fonts can also be different for each env, currently we need to create different index.html files for each env & replace it using fileReplacements config.