What is and how to use “base” path | Vite

Vite is a bundler that provides a fast development experience by using native ES modules, and in this article, we’ll dive into what base is and how to use it.

What is “base”

In Vite.js the base option in the vite.config.js file specifies the base URL for the application and where the modules are gonna be loaded from.

The default value of base if you don’t add the base parameter to vite.config.js will be / . Meaning the root directory.

How to use “base”

To configure base you can use an absolute path or a full URL as shown in the examples below:

Note: An absolute path is the location of a file or folder from the root directory(/).

export default defineConfig({
    //absolute path
    base: '/path/to/app/dir/',
    
    //full url
    base: 'https://www.example.com/my-app/'
});

You can also specify and overwrite the default or previously set base in the vite.config.js file by using a command line flag as shown here: vite build --base=/path/to/app/.

The command flag is very useful in case when you want to test in a different directory that you might have for staging.

To clear any confusion I will show a few examples of how the base path affects your setup.

export default defineConfig({
    //absolute path
    base: '/assets/dist/',
    //If you set the "base" as the example above then modules will be loaded from that path
});

As shown above, the modules will be loaded from:

https://www.example.com/assets/dist/

And it will look like this:

https://www.example.com/assets/dist/my_module.js

But if you don’t set the base and you happen to have your files inside /assets/dist the modules will try to be loaded from the root directory(/):

https://www.example.com/my_module.js and of course, your gonna get a 404.

This can be confusing in a way, I was a little confused at the beginning when I first came across base.

Don’t confuse outDir with base, these are two completely different things. The outDir property only indicates where files get built.

You can find more information about this in the official docs.

If you are starting to learn programming I suggest you read “The Best Way to Learn Programming”.

Any questions or comments you can leave them below in the comments section.

4 thoughts on “What is and how to use “base” path | Vite

  1. Andrew kov

    Great information, it cleared my doubts, just started learning Vite

Comments are closed.