發表於 程式分享

Angular使用環境變數-node

1.安裝@angular-builders/custom-webpack

npm install -D @angular-builders/custom-webpack

2.angular.json設定

"projects": {
    "name-of-the-project": {
      //...
      "architect": {
        "build": {
          "builder":"@angular-builders/custom-webpack:browser"_,
          "options": {
            "customWebpackConfig": {
                "path":"webpack.config.js"
            },
            //...
        //...
    }
}

3.webpack.config.js設定

const webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      $ENV: {
        publicPath: JSON.stringify((process.env['publicpath'] == undefined) ? "http://testepf.test.com.tw:4200/" : process.env['publicpath']),
        apiBaseUrl: JSON.stringify((process.env['apiBaseUrl'] == undefined) ? "http://127.0.0.1:8003/" : process.env['apiBaseUrl']),
      }
    })
  ]
};

4.新增typing.d.ts

export interface Env {
  apiBaseUrl: any;
  publicPath: string;
}

5.environment.prod.ts

import { Env } from "../typing";
declare var $ENV: Env;

export const environment = {
  production: false,
  publicPath: $ENV.publicPath,
};

參考: https://codinglatte.com/posts/angular/using-os-environment-variables-in-angular-with-docker/