Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline JavaScript and CSS with webpack

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'
};
like image 754
VJAI Avatar asked Sep 18 '16 08:09

VJAI


2 Answers

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
        ],
      },
    ],
  },
}
like image 180
IvanM Avatar answered Sep 18 '22 13:09

IvanM


use https://github.com/DustinJackson/html-webpack-inline-source-plugin

plugins: [
  new HtmlWebpackPlugin({
    inlineSource: '.(js|css)$' // embed all javascript and css inline
  }),
  new HtmlWebpackInlineSourcePlugin()
]  
like image 44
mastilver Avatar answered Sep 17 '22 13:09

mastilver