Search code examples
webpackwebpack-style-loadercss-loadersass-loader

Webpack loading CSS into individual <style> tags


I'm currently using the below Webpack config to import and parse the SCSS imports I make in my React components.

The crux of my issue is with the CSS part of the config. Currently, I'm importing SCSS files using their absolute file paths in their relevant React components. However on render, each individual CSS import gets their own <style> tag which results in a dozen <style> tags littered in the head of my web app. Is there a way to tweak the config such that the outputted CSS goes into one single <style> tag? And perhaps follow a specific entry into my app's React loading sequence with:

entry: {
  app: [
    '<React Component that's top of the render tree>',
  ],
},

I'm able to extract all the CSS into a single file, using the ExtractTextPlugin along with the style-loader module. However, that is intrinsically different from actually loading the CSS on the client.

const webpack = require('webpack');
const config = require('./webpack.client.base.config');

const devBuild = process.env.NODE_ENV !== 'production';

config.output = {
  filename: '[name]-bundle.js',
  path: '../app/assets/javascripts/generated',
  publicPath: '/assets/generated/',
};

config.module.loaders.push(
  {
    test: /\.jsx?$/,
    loader: 'babel-loader',
    exclude: /node_modules/,
  },
  {
    test: /\.css$/,
    loader: 'style!css',
  },
  {
    test: /\.scss$/,
    loader: 'style-loader!css-loader!postcss-loader!sass-loader',
  }
);

module.exports = config;

if (devBuild) {
  console.log('Webpack dev build for Rails'); // eslint-disable-line no-console
  module.exports.devtool = 'eval-source-map';
} else {
  config.plugins.push(
    new webpack.optimize.DedupePlugin()
  );
  console.log('Webpack production build for Rails'); // eslint-disable-line no-console
}

Here's a screenshot of what is currently happening on the client side: enter image description here

I've tried using the style-loader singleton option but it hasn't worked


Solution

  • {
      loader: 'style-loader'
      options: {
        singleton: true
      }
    }
    

    from https://www.npmjs.com/package/style-loader

    is that what you were looking?

    also (see comments) using style-loader?singleton can be used directly in older versions.