2

I have a web application built with webpack. I have many styling variations, and those styles are all called style.css and in their own respective directories like

  • ./STYLE_A/style.scss

  • ./STYLE_B/style.scss

  • ./STYLE_F/style.scss

    I am supplying a cross-env variable STYLE_DIR to webpack and I want that variable to control where the scss gets included from.

I've tried:

require(`./${STYLE_DIR}/style.scss`); //in the webpack (does nothing)

I've tried:

require(`./${STYLE_DIR}/style.scss`); //in my client.js (ends up including every style.scss from every one of the style directories)

I've tried setting this to a 'process.env' variable in webpack, I've tried using an alias to resolve, there's something I'm just missing.

1 Answer 1

1

I got interested in your question, then I did a little research and I think I have a way to make it work.

Steps:

1. In Webpack config file use DefinePlugin in order to have a constant that can be setup at compile time. You do that in this way:

const GLOBALS = {
  'process.env.STYLE_DIR': JSON.stringify(process.env.STYLE_DIR)
};

export default {
  entry: [
    './app/index'
  ],
  output: {
    path: path.resolve(__dirname, '/dist'),
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.DefinePlugin(GLOBALS)
  ],
  ...
}

2. Put your style.scss file in the correct folders (STYLE_A, STYLE_B and STYLE_C as you indicated).

3. In your .js file require your SCSS file as follow (of course be sure to have the corresponding loaders properly setup in Webpack config file):

require(`./${process.env.STYLE_DIR}/style.scss`);

4. Set the STYLE_DIR variable before you run webpack. Something like this:

export STYLE_DIR = 'STYLE_A'

This is working for me. If I change the STYLE_DIR value before running Webpack I get a different style file imported.

I hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for the answer, I think it's correct. Unfortunately, I'm always getting all of the .scss files concatenated in my final .css, so I thinks something else is sweeping the directories and gobbling up / including the .scss files. I need to do some more digging.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.