Anyone used webpack-dev-server? Cant figure out how to serve app

Hi All,

I have a project with the following structure:

├── build
│   └── bundle.js
├── client
│   ├── components
│   ├── index.js
│   ├── package-lock.json
│   ├── package.json
│   └── public
│       └── index.html
├── package-lock.json
├── package.json
├── server
│   ├── db
│   │   └── models
│   └── server.js
└── webpack.config.js

my webpack.config.js file looks as such:

var path = require('path');
var webpack = require('webpack');

module.exports = {
 entry: './client/index.js',
 output: { path: __dirname + '/build', filename: 'bundle.js' },
 module: {
  loaders: [
   {
    test: /.jsx?$/,
    loader: 'babel-loader',
    exclude: /node-modules/,
    query: {
     presets: ['es2015', 'react']
    }
   },
  ]
 },
 devServer: {
   contentBase: path.join(__dirname, "/client/public"),
   compress: true,
   port: 3000,
 }
};

The issue that I am running into is as follows:

When I open ./client/public/index.html in the browser, my react components are rendered and everything works as expected. To me this indicates that webpack is bundling correctly.

However, when i use webpack-dev-server and visit localhost:3000 in the browser nothing is there, just a blank page. The server is running but the App is not rendered.

I thought that in my webpack.config file by setting contentBase: path.join(__dirname, "/client/public") means that visiting localhost:3000 would serve the index.html file at /client/public/index.html. That html file is the one which runs my bundle via a script tag…which in turn should render all my react components (as it does when i open the html file in the browser). This is not the case however.

Could anyone help me out here?

Thanks!

Shouldn’t contentBase point to the directory where the bundle output is? I don’t know if this will work, but try changing the contentBase to the build directory, then add into your config this:

var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // ...
  plugins: [
    new HtmlWebpackPlugin({
      template: './client/public/index.html'
    })
  ],
  // ...
};

html-webpack-plugin handles adding appropriate <script> tags for you, so you might have to remove any <script> tags from the original index.html file.

1 Like

Thanks @kevcomedia.

With your suggestion I was able to figure this issue out (without using HtmlWebpackPlugin).

If anyone is curious as to how I resolved the issue:

  • set contentBase to point to the bundle output directory, /build.
  • in /build, create a copy of /client/public/index.html, this file will be served
  • this copied HTML file has a <script src="/bundle.js"> take to run the bundle contained in the same directory.

Thanks again!