M
M
Maxim Sokhryakov2019-05-20 20:56:38
JavaScript
Maxim Sokhryakov, 2019-05-20 20:56:38

Is it possible to substitute arbitrary data in custom js?

I have a script like this:

$(document).ready(function () {
    let allVideo = new window.VPlayer('192.168.1.67');
    /**
     * function (number, port, canvas_element, container)
     */
    allVideo.addVideo(0, 49002, $("#video-canvas-1").get(0), $('#jsmpeg1'));
    allVideo.addVideo(1, 49004, $("#video-canvas-2").get(0), $('#jsmpeg2'));
    allVideo.addVideo(2, 49006, $("#video-canvas-3").get(0), $('#jsmpeg3'));
    allVideo.addVideo(3, 49008, $("#video-canvas-4").get(0), $('#jsmpeg4'));

});

This script is custom. The express.js server will issue it.
The peculiarity is that the data '192.168.1.67' and 4900* change depending on certain reasons. It's inconvenient to edit them manually.
Therefore, it was decided to automate it.
In theory, this is seen as follows: the gulp\grunt build tool looks for an arbitrary template, and replaces it with its data obtained from the configuration json file.
The whole question is as follows:
1. Is the following gulp-jsfmt plugin suitable for current tasks?
2. Or are there template engines for js code, like handlebars and/or Mustache.js?
3. Or is it worth compiling this code in handlebars and inserting it into the page using a helper? (looks like a crutch).
4. Can TypeScript do this? (Request data to set up before converting it to js)
ps It's a bad idea to request this data from the server every time you connect. Although not significant, but an extra load on the server.
pss script format is clumsy, and it can be written more concisely, but that's a completely different story

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2019-05-20
@maximsohryakov

You are overthinking. Any template engine will help you - treat this file as a text file.
Env variables are now often used to configure JS on build.
further before assembly, SERVER_URL is set to the desired value in one of a ton of ways (this is a real environment variable) - at the output you get a js file with a substituted string.
It's comfortable and super flexible.
a common practice when building with webpack, I don’t know if gulp can do this, but I’m willing to bet that yes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question