Webpack 将 CSS 加载到单独的 <style> 标签中

标签 webpack webpack-style-loader css-loader sass-loader

我目前正在使用以下 Webpack 配置来导入和解析我在 React 组件中导入的 SCSS。

我的问题的症结在于配置的 CSS 部分。目前,我正在使用相关 React 组件中的绝对文件路径导入 SCSS 文件。但是在渲染时,每个单独的 CSS 导入都有自己的 <style>结果是一打 <style> 的标签标签散落在我的网络应用程序的头部。有没有办法调整配置,使输出的 CSS 成为一个单一的 <style>标签?并且可能在我的应用程序的 React 加载序列中使用以下特定条目:

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

我可以使用 ExtractTextPlugin 将所有 CSS 提取到一个文件中连同 style-loader模块。然而,这与在客户端实际加载 CSS 有本质上的不同。

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
}

这是客户端当前发生的情况的屏幕截图: enter image description here

我试过使用 style-loader singleton option但是没有用

最佳答案

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

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

这就是你要找的吗?

同样(见评论)使用 style-loader?singleton 可以直接在旧版本中使用。

关于Webpack 将 CSS 加载到单独的 &lt;style&gt; 标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44312069/

相关文章:

javascript - Webpack Angular 2 应用类型错误 : Cannot read property 'getOptional' of undefined

laravel - 找不到模块 : Error: Can't resolve 'fs'

css - Webpack 2 不会在 vue 文件中编译 css

css - 使用 Webpack 将样式表拆分为多个文件

javascript - 从 css-loader 启用 CSS 模块不允许导入 node_modules CSS

reactjs - react : Load component's CSS only when component is rendered

javascript - webpack 模块 Node 产生错误 EISDIR : illegal operation on a directory

node.js - 从 Grunt 任务设置 NODE_ENV

css - “You may need an appropriate loader to handle this file type” 与 Webpack 和 CSS

reactjs - 未定义的 css 模块类名