Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

240
Vistas
Webpack 5: How to inject CSS into head tag directly

I want to place CSS in the head tag of my HTML template directly instead of loading CSS into JS. But I can't find any reliable examples how to do this.

/* webpack.config.js */

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require("copy-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
  mode: 'development',
  entry: {
    main: path.resolve(__dirname, 'src/script.js'),
  },
  output: {
     path: path.resolve(__dirname, 'dist'),
     filename: '[name].[contenthash].js',
     clean: true,
  },
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin(),
    ],
  },
  module: {
    rules: [
      {test: /\.css$/, use: ['style-loader', 'css-loader']},
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'My optimized file',
      filename: 'index.html',
      template: path.resolve(__dirname, 'src/temp.html'),
      templateParameters: {
        'style': '[name].[contenthash].css' // doesn't bind with CopyPlugin
      },
    }),
    new CopyPlugin({
      patterns: [
        { from: path.resolve(__dirname, 'src/style.css'), to: '[name].[contenthash].css' },
      ],
    }),
  ],
};

And my HTML template src/temp.html:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title><%= htmlWebpackPlugin.options.title %></title>
   <link rel="stylesheet" href="<%= style %>">
</head>
<body>
   <h1>Hello there!</h1>
</body>
</html>

Now as the result in my compiled HTML file dist/index.html I get this:

<head>
  ...
  <link rel="stylesheet" href="[name].[contenthash].css">
</head>

After webpack build href attribute has just a wapback parameter [name].[contenthash].css instead of compiled CSS filename style.347572c74109b5f9ef4e.css.

And my folder structure:

dist
 ├─ index.html
 ├─ main.3d522b68c880128437a8.js
 └─ style.347572c74109b5f9ef4e.css
src
 ├─ script.js
 ├─ style.css
 └─ temp.html
webpack.config.js
package.json
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

For now I found temporary solution to this problem. I've just tried mini-css-extract-plugin and looked at example from html-webpack-plugin.

/* webpack.config.js */

...
  module: {
    rules: [
      { test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'] },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: 'template.html'
    }),
    new MiniCssExtractPlugin({ filename: 'style.css' })
  ]

But to make it work you must require CSS in JS file:

/* script.js */

require('./style.css');
...

But I'm still looking for how to do it without hardcoding CSS in JS using only webpack.config.js file since style.css has nothing to do with script.js in my case.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda