It can be helpful to have some minor differences between the production
and development environments. Primarily, in production it's common practice
to serve your API server and static assets via the same port, but it's much
more convenient to use different ports – or completely different urls –
locally. Vanilla Plus JS allows you to configure constants which depend on
if the server was built for production (vanillaplusjs build
)
or development (vanillaplusjs dev --watch
).
To enable this feature you will need to create the placeholder constants file,
which is typically used for type hints and is usually located at
src/public/js/constants.js
. Then it is
configured via vanillaplusjs.json
. The
default configuration is as follows (note that parts not pertaining to
constants are not shown):
{
"js_constants": {
"relpath": "src/public/js/constants.js",
"shared": {},
"dev": {
"API_URL": "http://127.0.0.1:8080"
},
"prod": {
"API_URL": ""
}
}
}
This will generate a file which depends on the environment. In development it would be:
export const API_URL = "http://127.0.0.1:8080";
And in production it would be:
export const API_URL = "";
This could be used, for example, to make a fetch wrapper as follows:
import { API_URL } from "/js/constants.js";
export function apiFetch(url, options) {
if (url.startsWith("/")) {
url = API_URL + url;
}
return fetch(url, options);
};
The constants dictionary will be initialized with the shared values and then updated with the environment values. The actual contents of the constants file in your src directory will be ignored, but the file must exist for the output to be generated.
You can also use environment variables for string values. For example, if you want to load the constant "STRIPE_CLIENT_ID" from the environment variable "STRIPE_CLIENT_ID", you could do:
{
"js_constants": {
"relpath": "src/public/js/constants.js",
"shared": {
"STRIPE_CLIENT_ID": "env://STRIPE_CLIENT_ID"
},
"dev": {},
"prod": {}
}
}