process.env.NODE_ENV variables into scss via webpack
Asked Answered
F

1

9

Is there a way to reference a process.env.NODE_ENV in a scss file by passing it to the sass-loader in web-pack. If so anyone know how to go about this ?

Here is my webpack module lodaers array.

module: {
    loaders: [
      { test: /\.js?$/,
        loader: 'babel-loader',
        include: path.join(__dirname, '../app'),
        exclude: /node_modules/
      },
      { test: /\.scss?$/,
        loader: 'style-loader!css-loader!sass-loader',
        include: path.join(__dirname, '../app', 'styles')
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        include : path.join(__dirname, '../app', 'images'),
        loader  : 'file-loader?limit=30000&name=[name].[ext]'
      },
      {
        test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
        include : path.join(__dirname, '../app', 'fonts'),
        loader: 'file-loader?name=fonts/[name].[ext]'
      }
    ] 

I even tried

      { test: /\.scss?$/,
        loader: 'style-loader!css-loader!sass-loader',
        include: path.join(__dirname, '../app', 'styles'),
        options: {
          data: "$env: " + process.env.NODE_ENV + ";"
        }
      }

but the above broke the build. I just want a way to access a url in my scss file depending on the environment. It doesn't have to be via webpack any ideas would help without hard coding it. for example:

  .contact-transparent{
    width: 100%;
    height: 100%;
    background: url(process.env.NODE_ENV+'/home-background.jpg') left center no-repeat;
  }
Fadil answered 1/5, 2017 at 17:50 Comment(0)
E
0

I think you could get this done with a custom loader that you chain in before the others for your Sass files. In that loader you would check the value of NODE_ENV and do a find/replace in the Sass source, where the replaced value is based on the env. Not fancy but would get the job done. For example:

// url-by-env-loader.js
module.exports = (source) => {
  const urlsByEnv = {
    dev: "the-dev-host.com",
    staging: "the-staging-host.com",
    prod: "the-prod-host.com"
  };
  const urlToReplace = "the-url-in-your-sass-source.com";
  const urlToUse = urlsByEnv[process.env.NODE_ENV];
  const replaceRegex = new RegExp(urlToReplace, 'g');  

  return source.replace(replaceRegex, urlToUse);
}
Entrammel answered 22/3, 2019 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.