Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import and read the contents of a CSS file as text (React/webpack)

What I'm trying to do is import the css file, read its contents, and then create an array of class names.

However, the following produces a log of empty object.

import TextCSS from './textfield.css'
console.log(TextCSS)

I've been searching the NPM for a package that could do that, Github and Google, tried a few packages with promising names, but so far nothing.

like image 477
Ska Avatar asked Jan 02 '26 08:01

Ska


1 Answers

create-react-app solution 2023

Code:

// eslint-disable-next-line import/no-webpack-loader-syntax
import css from '!!css-loader?{"sourceMap":false,"exportType":"string"}!./styles.css';

Explanation:

CRA uses Webpack under the hood, but does not allow editing webpack.config.js. Many solutions for this question recommend installing raw-loader which is deprecated as of 2021. The recommended migration solution is called asset modules, which requires editing the webpack.config.js file (again, we don't have access to it in CRA).

So the completely vanilla solution, without installing third-party packages that are not native to CRA, is to use inline loaders.

  1. Find the loader we need. In this example, it is css-loader. There are other options for different file types.

  2. Check the loader options to see if we can get the format we need, in this case a string. We confirm that there is a string option for our loader.

  3. Write the code with our desired options. Starting with a basic import:

     import css from './styles.css'
    

    we specify our desired loader:

     import css from '!!css-loader!./styles.css'
    

    and then pass our options in as a JSON object query parameter:

     import css from '!!css-loader?{"sourceMap":false,"exportType":"string"}!./styles.css'
    

    I set sourceMap option to false because if otherwise unspecified, the imported string contains a comment at the end containing compressed data about the file.

    Finally, command your linter to ignore the non-standard syntax:

     // eslint-disable-next-line import/no-webpack-loader-syntax
     import css from '!!css-loader?{"sourceMap":false,"exportType":"string"}!./styles.css';
    
like image 121
Raine Avatar answered Jan 03 '26 21:01

Raine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!