reactjsreact-routerwebpack-4

How to fix Uncaught DOMException: Failed to execute 'pushState' on 'History'


I have this little app that works fine in development mode with webpack-dev-server, but when I use the bundled files from the dist folder generated by the production mode, all I get in the browser is this error:

Uncaught DOMException: Failed to execute 'pushState' on 'History': A history state object with URL 'file:///C:/' cannot be created in a document with origin 'null' and URL 'file:///C:/Users/cristi/work/react_test_ground/dist/index.html'.

How can I solve this pushState problem?

Initially I tried to split the code with React.lazy and Suspense, since webpack was throwing this error:

WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
Assets:
  2c7b7b6becb423b8f2ae.bundle.js (413 KiB)

WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
Entrypoints:
  main (413 KiB)
      2c7b7b6becb423b8f2ae.bundle.js


WARNING in webpack performance recommendations:
You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of
your application.

But the problem persists.

You can see the code and the full repository here: https://github.com/cristiAndreiTarasi/temporary

App.js

import React, { Fragment, Suspense, lazy } from 'react';
import { BrowserRouter, Route, Link, Switch } from 'react-router-dom';

const Home = lazy(() => import('./Home'));
const Blog = lazy(() => import('./Blog'));
const Contact = lazy(() => import('./Contact'));

export default () => (
    <BrowserRouter>
        <div>
            <ul>
                <li><Link to='/'>Home</Link></li>
                <li><Link to='/blog'>Blog</Link></li>
                <li><Link to='/contact'>Contact</Link></li>
            </ul>

            <Suspense fallback={<p>Loading...</p>}>
                <Switch>
                    <Route exact path='/' component={Home} />
                    <Route path='/blog' component={Blog} />
                    <Route path='/contact' component={Contact} />
                </Switch>
            </Suspense>
        </div>
    </BrowserRouter>   
);

The format of the other components is this one:

import React from 'react';

export default () => (
    <div>
        <h1>Hello from the Blog</h1>
        <img src='../images/landscape-art_large.jpg' />
    </div>
);

I want to get the same result that I,m getting from the development mode, from the bundled files generated by the production mode.


Solution

  • You should open your files via an Webserver. Because you cannot change location history on the file:// api.