Webpack将CSS加载到单独的< style>标签 [英] Webpack loading CSS into individual <style> tags

查看:113
本文介绍了Webpack将CSS加载到单独的< style>标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用下面的Webpack配置导入和解析我在React组件中所做的SCSS导入.

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

我问题的症结在于配置的CSS部分.目前,我正在使用其相关React组件中的绝对文件路径导入SCSS文件.但是在渲染时,每个单独的CSS导入都会获得自己的<style>标签,这会在我的Web应用程序的头部散乱地出现许多<style>标签.有没有办法调整配置,使输出的CSS进入单个<style>标记?也许遵循以下命令进入我的应用程序的React加载序列中的特定条目:

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>',
  ],
},

我可以使用ExtractTextPluginstyle-loader模块将所有CSS提取到一个文件中.但是,这与在客户端上实际加载CSS本质上有所不同.

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:

我尝试使用样式加载器单例选项,但无效

推荐答案

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

来自 https://www.npmjs.com/package/style-loader

那是你在找什么吗?

也(请参阅注释)可以直接在较早的版本中使用.

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

这篇关于Webpack将CSS加载到单独的&lt; style&gt;标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆