Exploring the functionalities of command line arguments in Vue.js

Is there a way to set command line arguments for a Vue.js application? I am utilizing Vue 3 on the frontend which interacts with a Python backend (Flask) using Axios. Currently, I am defining the baseURL for Axios in my main.js file as follows:

import axios from 'axios'
axios.defaults.baseURL ='http://localhost:1234/';

For more versatility, I aim to retrieve the path ('http://localhost:1234/') from the command line, but I am unsure of how to accomplish this.

I start the frontend using npm in the following manner, specifying the host and port for the frontend:

npm run --prefix frontend dev -- --host frontendHostName --port frontendPortNumber

How can I enhance this process by introducing custom command line parameters for backend communication, such as --backendHost backendHostName etc.? And how can I access these parameters within my JavaScript code?

I am still new to JavaScript and Vue, and although I have reviewed some suggestions, I am struggling to find a solution to this issue.

Answer №1

One way to pass variables into your code is by setting them in the command line, but it's recommended to use an .env file instead.

While the .env file can have different suffixes for various environments, it's not commonly used because typically, you'll set up these variables on a docker, on the platform itself (like netlify, versel, ...).

Using the .env file method

To implement this method, create an .env file at the root of your project and access the variable values correctly with process.env.VariableName.

For example

const apiHostIp = process.env.VITE_API_HOST;
const apiHostPort = process.env.VITE_API_PORT;

axios.defaults.baseURL = "http://" + apiHostIp + ":" + apiHostPort + "/";

Using the command line method

If you prefer setting variables from the command line, install the library cross-env and modify your command as follows:

cross-env VITE_API_HOST=127.0.0.1 VITE_API_PORT=5000 YourCommand

Note: Remember that YourCommand represents the script to start the application found in package.json. If you are using vite, it should look similar to what's shown in package.json

"scripts": {
  "dev": "vite",
  "build": "vite build"
}

After updating, it will appear like this

"scripts": {
  "dev": "cross-env VITE_API_HOST=127.0.0.1 VITE_API_PORT=5000 vite",
  "build": "vite build"
}

In certain operating systems, there may be issues reading the defined variables as explained above (mostly in windows), which is why this method is essential.

For more information about the library cross-env, refer to this comment and the npm documentation of the library itself.

Answer №2

Here is my solution:

For my project, I decided to create a .env file at the root level alongside my index.html.

I specified the environment variables (which I believed should be treated as command line arguments) in this format:

VITE_API_HOST=127.0.0.1
VITE_API_PORT=5000

Then, accessing them in my main.js was straightforward:

const apiHostIp = import.meta.env.VITE_API_HOST;
const apiHostPort = import.meta.env.VITE_API_PORT;

axios.defaults.baseURL = "http://" + apiHostIp + ":" + apiHostPort + "/";

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

Tips for applying multiple colors to text within an option tag

I am currently struggling with adding a drop-down list to my form that displays 2 values, with the second value having a different text color (light gray). After some research, it seems like I need to use JavaScript for this customization. However, as I am ...

"Fill the designated area on the webpage with data retrieved from an external script

In my current project, I am utilizing Angular and JQuery to enhance re-usability by setting the header and footer as partials. However, I encountered an issue where I needed certain javascript functions to be executed within the footer upon loading - a tas ...

Is it possible to do bulk deletion in Flask Restless using AngularJS or JavaScript?

I am trying to implement bulk delete functionality in my AngularJS application by making an HTTP request to a Flask Restless API with version 0.17.0. While I know how to delete records one by one using their IDs in the URL, I am unsure if it is possible to ...

How to position radio buttons in line with labels containing inline inputs using Vue and Bootstrap

Currently, I am facing an issue with my form containing a radio button group where one of the radio button labels includes another numerical input. The layout is not aligned correctly, and I am struggling to adjust the spacing using CSS. I am unable to gr ...

Switching from using a computed property in Vue 2 to implementing the Vue 3 Composition API

I am currently in the process of updating my Vue 2 application to Vue 3 and I have been exploring how to work with computed properties using the Composition API in Vue 3. One particular challenge I am facing is migrating a Vue 2 computed property that pro ...

What is the most effective method for populating an array with all images from a particular directory?

I recently installed a pdf viewer plugin on my website (check it out here: ), and I have a question regarding its functionality. I am looking to include approximately 60 - 70 pages in this flip book, but I am unsure of how to proceed. I have attempted var ...

Tips for sorting through and minimizing data based on the most recent date

info = { start: 1, data: [ { name: 'Maria', date: '2020-02-15 }, { name: 'Paula', date: '2020-06-10 }, { name: 'Eva', date: '2020-12-05 }, { name: 'Sophia', date ...

How do I incorporate Spotify into my mobile app to enable seamless background music playback?

Currently engaged in a mobile app project that utilizes react-native for the frontend and nodeJS for the backend. The main objective is to enable users to seamlessly play Spotify songs directly within the app, even in the background. This enhancement will ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

What is the best way to incorporate user-provided values into a dynamic URL?

I am trying to create a feature where users can input a value and then click a button that will take them to a URL tailored to their entry. Here is my current code, but I am facing an issue - the user_input data does not seem to be passed to the URL when ...

Having trouble with CORS when trying to log in with Vue3/Axios on Flask backend

I am currently working on integrating a login system using Vue3/Axios. On the backend, I am utilizing Flask with CORS configured. crs.init_app(app, supports_credentials=True, origins=["http://127.0.0.1:3000"], resources={r"/api/v1/*"} ...

Importing a JavaScript file into another JavaScript file

var FS = require('fs'); var Path = require('path'); var Jsonfile = require('jsonfile'); var search = function () {}; search.prototype.projectContainerDirPath = null; /* * interface */ search.prototype.setPaths = function ...

Choosing several buttons in typescript is a skill that every programmer must possess

I need help with selecting multiple buttons in TypeScript. The code I tried doesn't seem to be working, so how can I achieve this? var input = document.getElementById('input'); var result = document.getElementById('result'); v ...

Trigger a function when <a> is clicked, which will then increment the count by one and reflect this change in the database

The database generates the content of this div ordered by a count number called "cts". Whenever I click on the div, I want the "cts" number to increase by one, and then update the change in the database. This will result in the content changing accordingly ...

Using SailsJS to populate attributes transmitted through socket.io's publishUpdate event

Utilizing the built-in socket capabilities of SailsJS has proved to be quite effective for me so far. However, I've encountered a challenge that I haven't been able to find any information on. In my model, I have set it up to populate certain at ...

Solving the problem of Axis label alignment in Three.js grid and techniques for visualizing x, y, z data on

I have been tasked with plotting well deviation surveys on a 3D grid. After referencing several articles online, I successfully created a 3D grid of the required size. However, I am currently struggling with positioning the labels for the x, y, and z axis ...

"Upon pressing the submit button in the router.post function, a null value appears

In my form, I am attempting to redirect the page to the home URL after clicking the submit button. However, using res.redirect('/home') is not achieving the desired result. I have also tried using console.log("testing");, but that is not working ...

Using JQuery's $.post function can be unreliable at times

Looking for help with a function that's giving me trouble: function Login() { var username = document.getElementById('username').value; var password = document.getElementById('password').value; $.post("Login.php", { ...

Dealing with URIError: Incorrect URI format encountered while using vue-router

While working on my website, I encountered a situation where appending % at the end of a URL resulted in a URIError: URI malformed. This issue sometimes caused the page to stop rendering. Despite using Vue-Router for routing, attempts with the router.befor ...

The JavaScript functions are not loading within the onload event handler

I've got an HTML document that contains some Script sections. I've consolidated all the functions within a single Script Tag. Now, I want to be able to utilize these methods in both the onload and onclick events. Below is the HTML file with all t ...