Inline JavaScript and CSS with webpack

VJAI picture VJAI · Sep 18, 2016 · Viewed 8.6k times · Source

I'm using Webpack for bundling resources. Currently it bundle both the CSS and JS files into a separate file called bundle.js. How can I make both the JS and CSS embedded inline in html file?

import HtmlWebpackPlugin from 'html-webpack-plugin';
import {HotModuleReplacementPlugin} from 'webpack';

export default {
  entry: {app: './test/dev'},
  module: {
    loaders: [
      {test: /\.js/, loader: 'babel-loader', exclude: /node_modules/},
      {test: /\.scss$/, loader: 'style!css!sass'}
    ]
  },
  plugins: [new HotModuleReplacementPlugin(), new HtmlWebpackPlugin()],
  devtool: 'eval-source-map'
};

Answer

IvanM picture IvanM · Jan 9, 2021

Use InlineChunkHtmlPlugin from react-dev-utils

const HtmlWebpackPlugin = require('html-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');

module.exports = {
  // ...
  output: { filename: 'client-bundle.js' },
  plugins: [
    new HtmlWebpackPlugin(),
    new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/client-bundle/]),
  ],
  // ...
};

*where "/client-bundle/" regex should match output filename

https://github.com/facebook/create-react-app/tree/master/packages/react-dev-utils#new-inlinechunkhtmlpluginhtmlwebpackplugin-htmlwebpackplugin-tests-regex


for inline css you need additional rules object:

module.exports = {
  entry: ['./src/style.css', './src/client.js'],
  // ...
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          'style-loader', // Creates `style` nodes from JS strings
          'css-loader', // Translates CSS into CommonJS
        ],
      },
    ],
  },
}