Search code examples
angular-cliangular-builderangularbuild

How to do a wildcard file replacement during build in angular projects?


I have an angular2+ project with scss styles. I'm targeting 2 apps: mobile (ionic) and web with the same codebase.

Due to the need to load totally different stylesheets for some of the components, I'm thinking to do the following: save web styles for each component in xxx.component.scss (no change), and save mobile styles for each component in xxx.component.mobile.scss

My question: is there a way to replace xxx.component.scss files with their xxx.component.mobile.scss counterpart when building the angular project, similar to what angular does with environment files (replaces environment.ts with environment.dev.ts if the configuration is dev)?

I tried using wildcards in angular.json like this, but it didn't work:

"fileReplacements": [
    {
      "replace": "src/environments/environment.ts",
      "with": "src/environments/environment.dev.ts"
    },
    {
      "replace": "src/**/*.scss",
      "with": "src/**/*.mobile.scss"
    }
  ]

Is there a way to do a wildcard file replacement during build in angular projects? What is the recommended way to do this?


Solution

  • This is not supported by angular.json. As a workaround, you can use the environment resolved in the environment file, and replace individual scss files inside the .ts file accordingly, as below:

    import { environment } from 'src/environment/envitonment';
    
    isIonic = environment.name === 'ionic';
    
    @Component({
      selector: 'app-xxx',
      templateUrl: './xxx.component.html',
      styleUrls: [ isIonic ? './xxx.component.mobile.css' : './xxx.component.css']
    })