angularangular-cliangular-hybrid

define a global sass variable with angular-cli


In my project, I need to inject a global variable to be used across the app, from an environment file, into SCSS files.

Following an advice such as this, isn't possible for me since the app contains ~50 different possible configs, so maintaining so many projects in angular.json is just not feasible.

In our current setup, using webpack, we used the data option for sass-loader to inject what ever variable imported from the environment file. This is currently impossible with angular-cli - making the migration impossible.

How can we achieve this?


Solution

  • I ended up succesfuly using ngx-build-plus, followed this article, and used this webpack.extra.js:

    const webpack = require('webpack');
    const configs = require('./src/configs');
    
    module.exports = {
      plugins: [new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)],
      resolve: {
        modules: ["node_modules"],
      },
      module: {
        rules: [
          {
            test: /\.scss$/,
            use: [
              {
                loader: 'sass-loader',
                options: {
                  sourceMap: true,
                  includePaths: ["src/ng1/assets/sass"],
                  data: `
                        $templateTheme: ${configs.templateTheme};
                      `,
                },
              },
            ],
          },
        ],
      },
    };