How I can set baseUrl for axios using npm param?
I would like to write command like this npm run build --baseUrl={url address} and in axios config set baseURL param to param from command.
It is possible ?
I don't think it is possible if you call that --baseUrl like that, as if you do it like that, you're going to have to define --baseUrl for npm start and other scripts, and you'll quickly end up with a spaghetti code.
I humbly suggest a way to mitigate this issue:
.env file that is filled with your environment variables for development. Add this to .gitignore and don't push this into your production server. This file is not used for production.BASE_URL variable, like:BASE_URL=http://YOUR_API_LOCATION/
Use libraries like dotenv (install by npm i dotenv) so you can read .env files.
Create a new utility for axios, let's say:
// client.js
const axios = require('axios');
const dotenv = require('dotenv');
// get all environment variables here.
dotenv.config({ path: '.env' });
// create a new axios instance with the base url from your '.env' file.
const axiosInstance = axios.create({
baseURL: process.env.BASE_URL,
/* other custom settings */
});
module.exports = axiosInstance;
You can reuse your axiosInstance like this:
// request.js
const axiosCustomClient = require('./client');
axiosCustomClient.get('relative/path/to/your/api');