Categories
Vue Answers

How to remove hashbang #! from URL with Vue.js?

Spread the love

To remove the hashbang (#!) from the URL in a Vue.js application, we can use the HTML5 history mode provided by Vue Router.

1. Enable HTML5 History Mode in Vue Router

In our Vue Router configuration (usually in router/index.js), set the mode option to 'history':

import Vue from "vue";
import Router from "vue-router";

Vue.use(Router);

export default new Router({
  mode: "history",
  routes: [
    // We routes here
  ],
});

By setting the mode to 'history', Vue Router will use the HTML5 history API to manipulate the browser’s history stack, allowing we to use clean URLs without the hashbang.

2. Configure Server for History Mode

When using history mode, we need to ensure that our server is configured to handle requests to non-existent URLs by serving the main index.html file.

This is because, without the hashbang, URLs that correspond to routes in our Vue app may not exist on the server.

For example, in a Vue CLI project with Vue Router, we typically add a catch-all route in our server configuration to serve the index.html file for all routes:

// Express.js example
const express = require("express");
const path = require("path");

const app = express();

// Serve static files
app.use(express.static(path.join(__dirname, "dist")));

// Handle all other routes
app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "dist", "index.html"));
});

// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

3. Build Our Vue App

Once we’ve configured Vue Router and our server, build our Vue.js application. If we’re using Vue CLI, we can run:

npm run build

This will create a production build of our app in the dist directory.

With these steps, our Vue.js application should now use clean URLs without the hashbang (#!).

However, ensure that our server is properly configured to handle routes when using HTML5 history mode.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *