如何强制 webpack 将纯 CSS 代码放入 HTML head 的 style 标签中?

如何强制 webpack 将纯 CSS 代码放入 HTML head 的 style 标签中?

问题描述:

我有这个webpack.config:

const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackInlineStylePlugin = require('html-webpack-inline-style-plugin');
const path = require('path');

module.exports = {
  mode: 'production',
  entry: {
    main: [
      './src/scss/main.scss'
    ]
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '',
    filename: 'js/[name].js'
  },
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        sourceMap: true
      })
    ]
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [
          'css-loader',
          'sass-loader',
        ]
      },
      // ... other stuffs for images
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/main.html',
      filename: 'main.html'
    }),
    new HtmlWebpackInlineStylePlugin()
  ]
};

我尝试过这种配置,但效果不佳,因为 CSS 代码已生成到 main.css 文件中.

I tried this configuration, but this isn't working well, because the CSS code is generated into the main.css file.

但是如果我将 CSS 代码作为 标签,它就可以工作了.

But if I write the CSS code directly into the <head> tag as a <style>, it's working.

如何设置 webpack 将 Sass 文件中的 CSS 代码作为内联 CSS 放入 HTML 中?

How can I set up the webpack to put the CSS code from Sass files into the HTML as inline CSS?

或者是否有一个勾号将CSS首先放入,然后html-webpack-inline-style-plugin插件可以解析它?

Or is there a tick to put the CSS first into the <head> and after this the html-webpack-inline-style-plugin plugin can parse it?

我以前只使用 style-loader 默认情况下会将您的 css 添加为 <head> 标记处的内联样式.这不会生成任何输出 css 文件,只会创建一个/多个样式标签,其中包含所有样式.

I've done this before only using style-loader that by default will add your css as style inline at <head> tag. This won't generate any output css file, this just will create one/multiple style tags with all you styles.

webpack.config.js

module.exports = {
  //... your config

  module: {
    rules: [
      {
        test: /\.scss$/, // or /\.css$/i if you aren't using sass
        use: [
          {
            loader: 'style-loader',
            options: { 
                insert: 'head', // insert style tag inside of <head>
                injectType: 'singletonStyleTag' // this is for wrap all your style in just one style tag
            },
          },
          "css-loader",
          "sass-loader"
        ],
      },
    ]
  },

  //... rest of your config
};

index.js(入口点脚本)

import './css/styles.css';