Answer the question
In order to leave comments, you need to log in
How to move JavaScript variable settings outside the repository?
Hello.
There is a website site.example.com. There is a server on which the ws.example.com web socket is raised. There are local computers of developers, there is a development server, which are on completely different domains.
JS scripts are collected by webpack.
How to specify the web socket connection address in some settings, but in such a way that the correct server gets into the collected file and works everywhere? At the same time, the settings could always be overridden locally or on the development server.
As in php (and almost everywhere on the backend, probably), let's say there is a config.php with basic settings that go into the repository. And there is config.local.php, which overrides what is needed and the file does not go to the repository. 2 files are merged and we get the settings that are needed on this particular server. Everyone is happy.
Taking into account the webpack, such a scheme will not work here - there will be the last one, that is dad.
How to be?
Answer the question
In order to leave comments, you need to log in
when building a webpack, you can specify the process.env.NODE_ENV assembly environment equal to production or development, relative to it you can resolve the values of certain variables
so far I see only such a solution.
on the backend side, in configs that are outside the repository, specify the websocket address. when assembling the page, substitute it in the data attribute of some html element. and common and the same for all js will read the address from this attribute and open the connection
Get a separate one config.js
, which is actually generated, for example, by the same PHP and contains what you need, depending on where the request came from.
If it's too rough, then:
<?php
echo "window.__appConfig = ".json_encode($frontConfig).";";
die();
Have you resolved your issue yet? And then the solution is not marked ((
I have the same problem, on the front I completely abandoned php and switched to HTML + JS (I really collect the bundle through gulp) and also encountered the problem that the gulp build task assembles the bundle, which should also work on locale and on the server, and I also wonder where I should store the path (in my case, to the API server)
I have so far come up with such a solution, there is gulpfile.js in which we do
1. two variables apiPathDev and apiPathProd
2. two tasks build-dev and build-prod
depending on what task is performed in it, substitution is performed in index.html in some element, for example, in the data-api-path="url-here" attribute,
and then js picks up this value at startup and places it in a variable
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question