2

I have a situation where I need to get the CSS string generated from a SASS file which has been compiled in JavaScript.

I have got a solution working with just CSS, using raw-loader

https://github.com/webpack-contrib/raw-loader

Using the following code...

import css from '!!raw-loader!../css/styles.css';
console.log(css);

However for this I need to compile the SCSS manually before I do this step which I don't really want to do.

I would prefer to do something like this... notice it is an SCSS rather than CSS file

import css from '!!raw-loader!../css/styles.scss';
console.log(css);

But this returns some JavaScript instead, I already have a SCSS loader in my webpack config which looks like this.

        {
            test: /\.s[ac]ss$/i,
            use: [
                {
                    loader: 'style-loader',
                    options: {
                        insert: 'head', // insert style tag inside of <head>
                        injectType: 'singletonStyleTag' // this is for wrap all your style in just one style tag
                    }
                },
                'css-loader',
                'sass-loader'
            ]
        },
5
  • Are you generating a CSS file from your SCSS? Commented Nov 28, 2019 at 10:51
  • no it's being compiled with webpack into js Commented Nov 28, 2019 at 10:52
  • Ok, so I don't think raw-loader would be suitable as that's for importing files (and you don't have actual files). Do you have an example of the output JavaScript webpack is generating? Commented Nov 28, 2019 at 11:43
  • Thanks for your comment, I have figured out how to do this, I have posted my answer below Commented Nov 28, 2019 at 13:02
  • That's great, glad you were able to find a solution Commented Nov 28, 2019 at 13:50

1 Answer 1

7

I have figured out how to do this...

import css from '!!css-loader!sass-loader!../css/styles.scss';

This puts it into an object which has the CSS as a string inside

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

2 Comments

Shouldn't it been import css from '!raw-loader!sass-loader!../css/styles.scss';?
If anyone trying to use this and getting an error this.getOptions is not a function. Use [email protected].

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.