Mihail H.
Mihail H.

Reputation: 1672

How to load a CSS into a JavaScript variable in Webpack 5?

I have

style.css

section {
    display: flex;
    background: url('./bg.svg');
}

script.mjs

import css from './style.css'
console.log(css)

webpack.config.mjs

import path from 'path'
import url from 'url';
import autoprefixer from 'autoprefixer'

const __dirname = path.dirname(url.fileURLToPath(import.meta.url))

export default {
  mode: 'production',
  context: path.resolve(__dirname),
  entry: path.resolve(__dirname, 'script.mjs'),
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: `[name].js`,
  },
  module: {
    rules: [
      {
        test: /\.(svg|png|jpg|jpeg)$/,
        type: 'asset/inline',
      },
      {
        test: /\.css$/,
        type: 'asset/source',
        use: [
          'css-loader',
          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                autoprefixer,
              ],
            },
          },
        ],
      },
    ],
  },
}

package.json

{
  "scripts": {
    "build": "webpack --config webpack.config.mjs"
  },
  "devDependencies": {
    "autoprefixer": "~10.2.5",
    "css-loader": "~5.2.4",
    "postcss-loader": "~5.2.0",
    "webpack": "~5.36.2",
    "webpack-cli": "~4.6.0"
  }
}

Expected console.log output

display: -webkit-box;display: -ms-flexbox;display: flex;background: url('data:image/svg+xml;utf8,...');

Actual result

I got the build error when the postcss-loader is present:

PostCSS Loader has been initialized using an options object that does not match the API schema"

And I got the wrong output in console.log when there is no postcss-loader in webpack.config.mjs:

// Imports
import ___CSS_LOADER_API_IMPORT___ from "./node_modules/css-loader/dist/runtime/api.js";
import ___CSS_LOADER_GET_URL_IMPORT___ from "./node_modules/css-loader/dist/runtime/getUrl.js";
import ___CSS_LOADER_URL_IMPORT_0___ from "./bg.svg";
var ___CSS_LOADER_EXPORT___ = ___CSS_LOADER_API_IMPORT___(function(i){return i[1]});
var ___CSS_LOADER_URL_REPLACEMENT_0___ = ___CSS_LOADER_GET_URL_IMPORT___(___CSS_LOADER_URL_IMPORT_0___);
// Module
___CSS_LOADER_EXPORT___.push([module.id, "section {\n\tdisplay: flex;\n\tbackground: url(" + ___CSS_LOADER_URL_REPLACEMENT_0___ + ");\n}", ""]);
// Exports
export default ___CSS_LOADER_EXPORT___;

Upvotes: 2

Views: 3341

Answers (1)

Subha
Subha

Reputation: 580

Please try these fixes for the two separate issues

  1. PostCSS Loader not initializing:
  //....{
        loader: "postcss-loader",
        options: {
          postcssOptions: {
            plugins: [
              autoprefixer,
            ],
          },
        },
      }, //....
  1. console is not logging expected out: Currently, the CSS file is loading but is not converted to a string and hence you see garbage in your console. You need systemjs/text plugin to load the text from the CSS file as a string.

At first do the following in your terminal

//install Systemjs
npm install systemjs
//install jspm
npm install [email protected] -g
// change over to your project directory
cd my-project
//intall jspm into your project
npm install [email protected] --save-dev
//initialise jspm
jspm init
//install text plugin
jspm install text

Then in your script.mjs

import './style.css!';
// Now, you can retrieve the contents of the file using the text plugin:
import css from './style.css!text';
console.log(css);

Please note: There are other ways of installing systemjs/text plugin as well. Please refer systemjs/text and systemjs for more installation info.

Upvotes: 1

Related Questions