Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject javascript entry point into html files with webpack dev server?

Is it possible to inject the JS entry point into the webpack dev server, much like the CSS is injected inline?

For example, my index.html is:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>app</title>
</head>
<body>
    <div id="app"></div>
</body>
</html>

But what I would like to see is, after running my webpack dev server, something like this (note that the CSS is injected automatically, although I do not see the js reference):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>app</title>
    <style>*,*:after,*:before{margin:0;padding:0}html{ /* .. all other styles */ }</style>
</head>
<body>
    <div id="app"></div>
    <script type="text/javascript" src="/js/app.js?1d8f26165af69413a6bb"></script>
</body>
</html>

Is this possible?

like image 777
bitten Avatar asked Sep 14 '25 05:09

bitten


1 Answers

Yes, its possible. You need to use HTML Webpack Plugin

The plugin will generate an HTML5 file for you that includes all your webpack bundles in the body using script tags. Just add the plugin to your webpack config as follows:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var webpackConfig = {
  entry: 'index.js',
  output: {
    path: 'dist',
    filename: 'index_bundle.js'
  },
  plugins: [new HtmlWebpackPlugin()]
};

This will generate a file dist/index.html containing the following:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Webpack App</title>
  </head>
  <body>
    <script src="index_bundle.js"></script>
  </body>
</html>
like image 196
Dmitriy Nevzorov Avatar answered Sep 16 '25 23:09

Dmitriy Nevzorov