Brandon Olivier Brandon Olivier - 5 months ago 50
Javascript Question

Webpack loads from the wrong URL when the path changes

I'm writing a react app and everything works fine when I navigate to

localhost:3000
, but when I try to go to
localhost:3000/foo/page
, I get an error message that tells me localhost:3000/foo/bundle.js cannot be loaded.

To me, this looks like a problem with Webpack looking in the wrong place for bundle.js, but I'm not sure. How do I get the app to always look at
localhost:3000
for bundle.js?

This is some of my webpack config.

var TARGET = process.env.npm_lifecycle_event;
var ROOT_PATH = path.resolve(__dirname);
var APP_PATH = path.resolve(ROOT_PATH, 'app');
var BUILD_PATH = path.resolve(ROOT_PATH, 'dist');

process.env.BABEL_ENV = TARGET;
var common = {
entry: APP_PATH,

output: {
path: BUILD_PATH,
filename: 'bundle.js'
},

module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['babel'],
include: APP_PATH
},
{
test: /\.svg$/,
loader: 'url-loader?limit=8192',
include: APP_PATH
},
{
test: /\.png$/,
loader: 'url-loader?limit=8192',
include: APP_PATH
},
{
test: /\.ico$/,
loader: 'url-loader?limit=8192',
include: APP_PATH
}
]
},

plugins: [
new HtmlWebpackPlugin({
title: 'foobar',
template: path.resolve(APP_PATH, 'index.html'),
favicon: path.resolve(APP_PATH, 'images', 'favicon.ico')
})
]
};

if (TARGET === 'start' || !TARGET) {
module.exports = merge(common, {
devtool: 'eval-source-map',
module: {
loaders: [
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass'],
include: APP_PATH
}
]
},
devServer: {
historyApiFallback: true,
hot: true,
inline: true,
port: 3000,
progress: true
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
});
}

Answer

Add output.publicPath: '/' to your webpack config.

output: {
  path: BUILD_PATH,
  publicPath: '/',
  filename: 'bundle.js'
}

HtmlWebpackPlugin most probably generates the file which have:

<script src="bundle.js"></script>

Setting up output.publicPath: '/' will make it:

<script src="/bundle.js"></script>

From Webpack Config page:

output.publicPath

The publicPath specifies the public URL address of the output files when referenced in a browser. For loaders that embed or tags or reference assets like images, publicPath is used as the href or url() to the file when it’s different then their location on disk (as specified by path). This can be helpful when you want to host some or all output files on a different domain or on a CDN. The Webpack Dev Server also takes a hint from publicPath using it to determine where to serve the output files from. As with path you can use the [hash] substitution for a better caching profile.

Comments