Configuring environments for a Vue3 project in both development and production

I recently created a Vue3 vite project, following the given instructions. However, I noticed that the method I used did not generate any env.development or env.production files, leaving me with little context when referring to the documentation. I assume that there should be something included in those files, but what exactly?

Although the project compiles successfully, it encounters an error with the router setup as shown below:

import { createWebHistory, createRouter, RouteRecordRaw } from "vue-router";

const history = createWebHistory();
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "Appointments",
    component: () => import("../views/Appointments.vue"),
  },
  {
    path: "/pets",
    name: "Appointments",
    component: () => import("../views/Pets.vue"),
  },
  {
    path: "/Claims",
    name: "Claims",
    component: () => import("../views/Claims.vue"),
  },
];
const router = createRouter({
  //fails on this line:
  history: createWebHistory(process.env.BASE_URL),
  routes,
});
  
export default router;  

I am struggling to figure out how to set the base URL correctly. Any suggestions?

Answer №1

It is essential to manually include the .env files, such as .env.development, in your project directory. However, setting the BASE_URL does not require these files, as it is automatically configured through the base configuration in the vite.config.js:

import { defineConfig } from 'vite'

export default defineConfig({
  base: process.env.NODE_ENV === 'development'
         ? '/my/dev/baseurl/'
         : '/my/prod/baseurl/',
})

When referencing environment variables in your source code, use import.meta.env instead of process.env:

// createWebHistory(process.env.BASE_URL), ❌
createWebHistory(import.meta.env.BASE_URL), ✅ 

Check out this demo for more details.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues arise when attempting to override attributes within the HTML of a parent component in Angular

Why does overriding an attribute in a child class that extends from another not work as expected? Here's a made-up scenario to simplify the issue: Parent class file: gridbase.component.ts import { Component, OnInit } from '@angular/core'; ...

The proper method for updating data on a backend API using Axios and Vue

I am working on a Vue application that includes several form fields. I want to ensure that any changes made by the user are saved in real-time to a backend database using a REST API with Axios, without requiring the user to click a save button. I have two ...

Having trouble with code behaving differently than expected in Chrome's debugger

I've come across a peculiar issue in my TypeScript project (an Angular application). Here's the code snippet that's causing trouble: const idx = myclone.findIndex(x => x.id === action.id); const hasVal = idx>-1; // for some reason, Chr ...

Binding values in Vue.js with a prefix and suffixCreating bindings in Vue

I attempted to bind a value to an input by using a variable declared in the data object, but I also need to include a prefix and a suffix. <input id="topnavback", v-bind:value="rgb({{themestopnavback}})", class="jscolor"/> The value "themestopnavba ...

The request/response is missing property "x" in type "y" but it is required in type "z" during fetch operation

I have configured an interface specifically for utilization with an asynchronous function: interface PostScriptTagResponse { script_tag : { readonly id : number , src : string , event : string , readonly created_at : string , readonl ...

Using Typescript: Generate keys in function return depending on parameter

Currently in the process of developing an SDK for a Rest API that includes an embed request parameter to fetch additional resources and add them to the response. I am exploring if there is a way, using Typescript, to extract these embed parameters while de ...

Have the getter functions for reactive objects in Vue 3 been transformed into computed values?

Is the memoization of bookCount in this instance handled equivalently to a computed reference? const author = reactive({ name: 'John Doe', books: [ 'Vue 2 - Advanced Guide', 'Vue 3 - Basic Guide', 'Vue 4 - ...

"Using axios and async/await in VUE.JS to perform multiple asynchronous GET

Perhaps this is a somewhat basic inquiry, as I am still learning the ropes of vue.js and javascript. Please bear with me if my question is not well-articulated or if the solution is straightforward... I am facing an issue where I need to retrieve data from ...

Guide to Rolling a Set of 5 Dice

I am looking to develop a game involving 5 dice. I have already created a function to roll one die using a random method, but I am unsure how to extend this functionality to the remaining four dice without having to create a separate method for each one. ...

Update the nest-cli.json configuration to ensure that non-TypeScript files are included in the dist directory

I've been searching for a solution for hours now: I'm developing an email service using nestJS and nest mailer. Everything was working fine until I tried to include a template in my emails. These templates are hbs files located in src/mail/templ ...

Validating a field conditionally upon submission

Adding a required validation conditionally to the "imageString" field upon submission, but the expected required validation is not being set. Initializing the form. constructor(){ this.poeForm = this.fb.group({ imageString: [""], imageFileNam ...

Using Fixed Patterns and Combining Types in an Interface

Presently, I am working with this interface: export interface User{ name: string birthday: number | Timestamp ... } When strictTemplates:false is enabled, I have no issue using this interface for server data retrieval with the birthday parameter in ...

What could be the reason for Vue router-link failing to work when clicked?

My nav bar component is designed to link to the about page view, but I am experiencing an issue. Despite Chrome indicating that the router-link element should lead to the correct destination when hovered over, clicking on a link does not navigate to the ab ...

Utilizing Typescript to extract type information from both keys and values of an object

I have a unique challenge of mapping two sets of string values from one constant object to another. The goal is to generate two distinct types: one for keys and one for values. const KeyToVal = { MyKey1: 'myValue1', MyKey2: 'myValue ...

Using Vue.js to bind a class to a component through a prop

Incorporating a color attribute via prop into a component is my current challenge. This attribute will determine the background color of the component, with the available options being 'red' and 'blue'. The structure of the component i ...

Troubleshooting the 'Buffer' name not found error occurring in an Angular application

While working on my application, I started encountering this error message out of nowhere. Everything was functioning correctly before, and I'm clueless as to what could have caused these errors to pop up. I attempted to address the issue by installin ...

Enhancing appearance with $refs?

Having trouble adding style to the $refs attribute. I keep getting an error message saying "Cannot set property 'cssText' of undefined." Is there a way to accomplish this task? I haven't come across anything similar to this issue before. th ...

Troubles arise when compiling TypeScript to JavaScript

I have been experimenting with TypeScript, specifically for working with classes. However, I am facing an issue after compiling my TS file into JS. Below is the TypeScript code for my class (PartenaireTSModel.ts): export namespace Partenaires { export ...

Add a feature to a functional component that is enclosed with React.forwardRef

Within my codebase, there exists a component that is wrapped with React.forwardRef and serves as a compound component. One challenge I encountered was how to preserve the functionality of Form.Item = FormItem; while still having the Form component fun ...

Specialized Character Formats in TypeScript

In my quest to enhance the clarity in distinguishing different types of strings within my program - such as absolute paths and relative paths, I am seeking a solution that ensures functions can only take or return specific types without errors. Consider t ...