It's possible to insert angular environment variable into scss?

与世无争的帅哥 提交于 2020-01-01 19:52:15

问题


I'm trying to find a way to change how my scss is compiled based on a "profile" variable environment. My app will be installed on different locations, witch with different theme, but all the css is the same. I just need to change what color palette will be used, during compilation. My app already have on the environments.ts a profile variable, that will be used for brand image.

I was thinking in something like:

export const environment = {
  production: true,
  profile: 'appX'
  apiUrl: 'http://mydoainX.com/api/',
};

and, on the scss:

$profile: environment.profile;

It's possible to do something like this?

Any thoughts?


回答1:


Eventually a found this question, witch lead me to the solution.

It says to create multiple apps with different .scss file in .angular-cli.json.

Step 1: Create several folders with .scss file for each environment, all the .scss files has the same filename:

|- src
  ...
  |- environments
    |- app1
      |- scss
        |- globalVars.scss
      |- environment.dev.ts
      |- environment.prod.ts
    |- app2
      |- scss
        |- globalVars.scss
      |- environment.dev.ts
      |- environment.prod.ts
  ...

in src/environments/app1/scss/globalVars.scss: $profile: 'app1'.

in src/environments/app2/scss/globalVars.scss: $profile: 'app2'.

Step 2:

Add multiple apps in .angular-cli.json ( Angular-cli Wiki Here ), and add stylePreprocessorOptions entry in each app object for each environment ( Angular-cli Wiki Here ).

"apps": [
  {
    ...
    "name": "app1",
    "environments": {
      "dev": "environments/app1/environment.dev.ts",
      "prod": "environments/app1/environment.prod.ts"
    },
    "stylePreprocessorOptions": {
      "includePaths": [
        "environments/app1/scss"
      ]
    }
    ...
  },
  {
    ...
    "name": "app2",
    "environments": {
      "dev": "environments/app2/environment.dev.ts",
      "prod": "environments/app2/environment.prod.ts"
    },
    "stylePreprocessorOptions": {
      "includePaths": [
        "environments/app2/scss"
      ]
    }
    ...
  },
  ...
],

Step 3:

Import the globalVars.scss where the env-specific variables needed. Do not use the relative path!

@import "globalVars";

When using ng build --app=app1, the $profile will be 'app1'and so on.

Step 4: On my theme.scss i used the variable like this:

.my-style {
  @if $profile == 'app1' {@include angular-material-theme($theme-app1);}
  @if $profile == 'app2' {@include angular-material-theme($theme-app2);}

  &.contrast {
    @include angular-material-theme($theme-contrast);
  }
}


来源:https://stackoverflow.com/questions/46852550/its-possible-to-insert-angular-environment-variable-into-scss

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!