使用 Webpack 在输出 html 中非 JS 注入 <style> 标签

问题描述

我有一个有趣的用例,我需要一个 webpack 构建,它将在我的 index.html 文件中注入样式标记,就像使用 style-loader 一样......但直接插入 HTML 而不是使用 js 包。知道如何做到这一点吗?如下配置使用javascript注入样式标签:

const path = require('path')
const HtmlWebPackPlugin = require('html-webpack-plugin')

module.exports = {
  output: {
    publicPath: ''
  },module: {
    rules: [
      {
        test: /\.html$/,use: [
          {
            loader: 'html-loader',}
        ]
      },{
        test: /\.css$/,use: [
            'style-loader','css-loader'
        ]
      },{
        test: /\.scss$/,'css-loader','sass-loader'
        ]
      },{
        test: /\.svg$/i,include: /.*_sprite\.svg/,use: [
            {
                loader: 'svg-sprite-loader',options: {
                    publicPath: '',}
            }
        ]
      },{
        test: /\.(png|jpe?g|gif)$/i,use: [
          {
            loader: 'file-loader',},],}
    ]
  },plugins: [
    new HtmlWebPackPlugin({
      template: './src/index.html',filename: './index.html'
    })
  ]
}

extract-loader 提取 css 字符串...但不知道如何将其输入到 html 文件中。

有什么想法吗?

解决方法

如果有人想要这个问题的答案,已经找到了。

webpack.config.js

const path = require('path')
const HtmlWebPackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  output: {
    publicPath: ''
  },module: {
    rules: [
      {
        test: /\.css$/,use: [
            'style-loader','css-loader'
        ]
      },{
        test: /\.scss$/,use: [
          MiniCssExtractPlugin.loader,'css-loader','sass-loader'
        ]
      },{
        test: /\.svg$/i,include: /.*_sprite\.svg/,use: [
            {
                loader: 'svg-sprite-loader',options: {
                    publicPath: '',}
            }
        ]
      },{
        test: /\.(png|jpe?g|gif)$/i,use: [
          {
            loader: 'file-loader',},],}
    ]
  },plugins: [
    new HtmlWebPackPlugin({
      template: './src/index.html',filename: './index.html',}),new MiniCssExtractPlugin({
      filename: '[name].[contenthash].css'
    })
  ]
}

在 ./src/index.html 的头部:


    <style>
        <%= compilation.assets[htmlWebpackPlugin.files.css].source()  %>
    </style>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...