How to Run Vue 3 in a Subdirectory

You don’t always have to deploy Vue into the root domain. Learn how to deploy and run Vue 3 inside a subdirectory.

How to run Vue 3 in a Subdirectory

By default, Vue will assume that you are deploying it to the root of a domain. However, this may not always be your intention. There are plenty of scenarios where you want to deploy your project’s production build inside a domain subdirectory. You may be deploying multiple Vue projects into a single domain. Or you might be nesting Vue into a completely separate project or framework. For either case, here is how to run Vue 3 in a subdirectory. 

How to Run Vue 3 in a Subdirectory

To deploy Vue 3 in a subdirectory, set the “publicPath” property in your vue.config.js file.

//vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  publicPath: '/yoursubdirectory',
})

If there is no vue.config.js file at the root of your project, create the file and add the publicPath property. This property is available if you are using Vue CLI 3.3 or greater. Before Vue CLI 3.3, this property was referred to as baseURL. By default, the value of publicPath will be set to “/” which is the root path of the domain. Whatever you enter into the property value will become your project’s new root operating directory. When running the development server, it will now follow the specified path.

http://localhost:8080/yoursubdirectory

When you deploy your project’s production build, your assets will be served from the specified subdirectory.

http://yourdomain.com/yoursubdirectory

The publicPath parameter can also accept conditional logic, so if you only want to change the value for the production build of your project, you can use the following code:

//vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  publicPath: process.env.NODE_ENV === 'production' ? '/yoursubdirectory' : '/',
})

With this conditional logic, your development environment will continue to use the default root path, but your production build will switch the publicPath to your specified directory.

Now you can upload your dist files directly into a subdirectory folder on your production server and have your application run without any issues. For more details about the publicPath property and others, check out the official Vue CLI documentation for the vue.config.js file.

We hope you found this guide helpful. Check out more guides on VueJS and Javascript in our Javascript coding section.