3

I am using historyApiFallback: true to redirect all non-existing urls to index page. It is working fine for 1st level route, say localhost:8080/abc . But when I try localhost:8080/abc/xyz , I get error in browser console which says

http://localhost:8080/abc/scripts/bundle.js 404 (Not Found)

Webpack config is

const path = require('path');

module.exports = {
    entry:"./src/app.js",
    output:{
        path:path.join(__dirname,'public','scripts'),
        filename:'bundle.js'
    },
    module:{
        rules:[{
            test:/\.js$/,
            exclude:/node_modules/,
            loader:'babel-loader'
        }]
    },
    devServer:{
        contentBase:path.join(__dirname,'public'),
        publicPath:'/scripts/',
        historyApiFallback: true
    }
}

Index page

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div id="app">
        hello
    </div>
</body>
<script type="text/javascript" src="scripts/bundle.js"></script>
</html>

Folder structure is

-node_modules/
-public/
    -scripts/
    -index.html
-src/
    -app.js
-package.json
-webpack.config.js

What am I missing?

Liam
  • 27,717
  • 28
  • 128
  • 190
Farhan Haque
  • 991
  • 1
  • 9
  • 21

2 Answers2

2

The missing forward slash in the script tag in html was causing the problem. This helped me solve the problem.

Farhan Haque
  • 991
  • 1
  • 9
  • 21
1

You can refine the behaviour further using rewrites. From the documentation:

historyApiFallback: {
  rewrites: [
    { from: /^\/$/, to: '/views/landing.html' },
    { from: /^\/subpage/, to: '/views/subpage.html' },
    { from: /./, to: '/views/404.html' }
  ]
}
Geek Stocks
  • 2,010
  • 3
  • 27
  • 43
  • 1
    I have added - rewrites: [ { from: /^\/[a-z]*/, to: '/index.html' }, ] now index is getting served from localhost:8080/abc/xyz but bundle.js does not contain the compiled code written in app.js, instead it contains the html content. – Farhan Haque Mar 10 '18 at 11:00
  • Glad your devServer is working now. Sounds like you have a new question, that is going to be a different issue. I use [html-webpack-plugin](http://webpack.js.org/plugins/html-webpack-plugin/) to pack html content. – Geek Stocks Mar 10 '18 at 11:08
  • using rewrite we can have specific fallback but it didn't solved my problem. Later on I realised what was going wrong. It was just adding a forward slash at the start in script tag in html which worked fine with historyApiFallback: true. – Farhan Haque Mar 11 '18 at 12:57