Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Angular CLI pass environment-specific settings to Sass variables?

When building an Angular 2 app using Angular CLI/webpack, I'd like to specify values for a few Sass variables. Like make some url(#{$my-base-path}/...) or $fa-font-path point to a CDN in production, or simply set different background colors for acceptance and production builds.

I like how Angular CLI picks a config from, e.g., environments/environment.prod.ts. But I'd also happily use additional command line parameters for ng build, but no luck so far:

  • Without Angular CLI, I guess I could use Sass custom functions on the command line, but I don't know how I could use that approach along with Angular CLI.

  • Maybe I can specify the path to some specific my-variables.sccs to use for all Sass compilations?

  • Webpack's sass-loader states the following, but I've no clue if I can use that with Angular CLI:

    Environment variables

    If you want to prepend Sass code before the actual entry file, you can simply set the data option. In this case, the sass-loader will not override the data option but just append the entry's content. This is especially useful when some of your Sass variables depend on the environment:

    {
        loader: "sass-loader",
        options: {
            data: "$env: " + process.env.NODE_ENV + ";"
        }
    }
    

Any idea?

like image 900
Arjan Avatar asked Feb 28 '17 18:02

Arjan


1 Answers

In addition to the comment by Arjan I solved the problem by creating 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
    |- environment-scss
      |- globalVars.scss
    |- environment-prod-scss
      |- globalVars.scss
  ...

in src/environment-scss/globalVars.scss:

  $my-base-path: 'YOUR/DEV/PATH'

in src/environment-prod-scss/globalVars.scss:

  $my-base-path: 'YOUR/PROD/PATH'

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": [
  {
    "root": "src",
    ...
    "name": "dev",
    "stylePreprocessorOptions": {
      "includePaths": [
        "environments/environment-scss"
      ]
    }
    ...
  },
  {
    "root": "src",
    ...
    "name": "prod",
    "stylePreprocessorOptions": {
      "includePaths": [
        "environments/environment-prod-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=dev, the $my-base-path will be 'YOUR/DEV/PATH', when using ng build --app=prod, the $my-base-path will be 'YOUR/PROD/PATH'

like image 137
phuud Avatar answered Nov 03 '22 09:11

phuud