DEV Community

Guilherme Siquinelli
Guilherme Siquinelli

Posted on

3 1

ENV vars with Angular & Nx

Primeiro, instale @types/node para que possamos usar process.env em nosso código.

npm install --save-dev @types/node

# Or with yarn
yarn add --dev @types/node
Enter fullscreen mode Exit fullscreen mode

Em seguida, atualize os targets build e serve (no arquivo project.json ou angular.json), para o seguinte.

{
  "build": {
    // NOTA: altere o executor para um que suporte configurações personalizadas do webpack.
    "executor": "@nrwl/angular:webpack-browser",
    // recorte
    "options": {
      // NOTE: This file needs to be created.
      "customWebpackConfig": {
        "path": "apps/myapp/webpack.config.js"
      }
      // recorte
    }
  },
  "serve": {
    // NOTA: altere o executor para um que suporte configurações personalizadas do webpack.
    "executor": "@nrwl/angular:webpack-server"
    // recorte
  }
}
Enter fullscreen mode Exit fullscreen mode

Então, podemos usar DefinePlugin em nossa configuração webpack personalizada.

// apps/myapp/webpack.config.js
const webpack = require('webpack');

function getClientEnvironment(configuration) {
  // Grab NODE_ENV and MY_APP_* environment variables and prepare them to be
  // injected into the application via DefinePlugin in webpack configuration.
  const MY_APP = /^MY_APP_/i;

  const raw = Object.keys(process.env)
    .filter((key) => MY_APP.test(key))
    .reduce(
      (env, key) => {
        env[key] = process.env[key];
        return env;
      },
      {
        NODE_ENV: process.env.NODE_ENV || configuration,
      }
    );

  // Stringify all values so we can feed into webpack DefinePlugin
  return {
    'process.env': Object.keys(raw).reduce((env, key) => {
      env[key] = JSON.stringify(raw[key]);
      return env;
    }, {}),
  };
}

module.exports = (config, options, context) => {
  config.plugins.push(
    new webpack.DefinePlugin(getClientEnvironment(context.configuration))
  );
  return config;
};
Enter fullscreen mode Exit fullscreen mode

Agora, quando definimos variáveis ​​em nosso arquivo .env, como...

# apps/myapp/.env
MY_APP_API_URL=http://localhost:3333
Enter fullscreen mode Exit fullscreen mode

Finalmente, podemos usar variáveis ​​de ambiente em nosso código. Por exemplo:

// apps/myapp/src/main.ts
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

if (process.env['NODE_ENV'] === 'production') {
  enableProdMode();
}

// This is defined in our .env file.
console.log('>>> MY_APP_API_URL', process.env['MY_APP_API_URL']);

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch((err) => console.error(err));
Enter fullscreen mode Exit fullscreen mode

Você também deve atualizar os arquivos tsconfig.app.json e tsconfig.spec.json para incluir tipos do node.

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    // recorte
    "types": ["node"]
  }
  // recorte
}
Enter fullscreen mode Exit fullscreen mode

Agora basta servir a aplicação e sua variável estará no console do browser : )


Nota:
Isso foi testado em ambiente com versões:

  "@nrwl/angular": "^14.4.3",
  "@nrwl/workspace": "14.4.3"

valeu
[]s

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay