Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Webpack with React-router bundle.js Not Found

I build a project with Webpack and react-rounter. this is my code:

ReactDOM.render(
    <Provider store={store}>
        <Router history={ browserHistory }>
            <Route path='/' component={ App } >
                <IndexRoute component={ Home } />
                <Route path="purchase" component={ Purchase } />
                <Route path="purchase/:id" component={ Purchase } />
            </Route>
        </Router>
    </Provider>,
    document.getElementById('example')
);

When i request "http://127.0.0.1:3001/purchase", it's work! but the address "http://127.0.0.1:3001/purchase/a" has error. look the error message:enter image description here

My WebpackDevServer config is:

new WebpackDevServer (webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    noInfo: false,
    historyApiFallback: true
}).listen(3001, '127.0.0.1', function (err, result) {
        if (err) {
            console.log(err);
        }
        console.log('Listening at localhost:3001');
    });

I don't know what the matter, Help me!

like image 582
Xiaoguang Song Avatar asked Jun 22 '16 08:06

Xiaoguang Song


2 Answers

You are using a relative path to describe path of the bundle.js in your index.html.

You should use absolute path for bundle.js in your index.html

Absolute path contains the root directory and all other subdirectories in which a file or folder is contained.

If it's in the same path with your index.html.

eg.

public/index.html

public/bundle.js

This would solve your problem.

<script src="/bundle.js"></script>
like image 147
Seyhan Avatar answered Sep 22 '22 11:09

Seyhan


If you happen to be using the HtmlWebpackPlugin editing directly index.html is not an option. So, to fix this particular issue, add publicPath and specify / as the root folder inside webpack.config.js:

const path = require('path')

module.exports = {
  entry: './app/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/'
  },
  // more config stuff goes below..
} 

Don't forget to restart the webpack dev server for these changes to take effect

More info about publicPath here.

like image 38
Juan Marco Avatar answered Sep 24 '22 11:09

Juan Marco