How to force webpack to put the plain CSS code into HTML head's style tag?

耗尽温柔 提交于 2020-02-03 10:18:14

问题


I have this 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()
  ]
};

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

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

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

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?


回答1:


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$/,
        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 (entry point script)

import './css/styles.css';


来源:https://stackoverflow.com/questions/53653652/how-to-force-webpack-to-put-the-plain-css-code-into-html-heads-style-tag

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