Router links problem when hosting VueJS project

Viewed 528

I'm having a VueJS website project with router links. Locally everything works as expected, however when I build it for hosting the routing links no longer work. (I tried two different hosting platforms, so the problem is in my configs for sure.)

I already read some similar questions and all suggested the history mode. I'm already using it and it's not working.

My router index.js file:

Vue.use(Router)

export default new Router({
    linkActiveClass: 'active',
    routes: configRoutes(),
    mode: 'history',
})

function configRoutes() {
    return [
        {
            path: '/',
            name: 'Home',
            component: Home,
        },
        {
            path: '/about',
            name: 'About',
            component: About,
        },
        {
            path: '/contact',
            name: 'Contact',
            component: Contact,
        },
    ]
}

and my config index.js for the build:

build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',

    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
1 Answers

the problem is with: mode: 'history' in your router

According to vue router documentation:

The default mode for Vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes.

To get rid of the hash, we can use the router's history mode

Here comes a problem Since Vue is SPA, without a proper server configuration, the users will get a 404 error if they access any route "other than root directory"

Solution

to solve this problem: you have two solutions:

  1. make your host redirect to index.html after each fallback (read Example Server Configurations in router documentation)
  2. remove mode: 'history' from Router configuration, this will add hash after base URL. so all routes will be found
Related