Webpack loading CSS into individual <style> tags

半世苍凉 提交于 2019-12-23 15:46:13

问题


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:

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


回答1:


{
  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.




回答2:


If you are using style-loader v1.0.0, "singleton" option was removed. You can use "injectType" instead.

{
  loader: 'style-loader',
  options: {
    injectType: 'singletonStyleTag',
  }
}


来源:https://stackoverflow.com/questions/44312069/webpack-loading-css-into-individual-style-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!