Home > front end >  Vite 3: defining a global variable in the config adds a newline at the end of the string
Vite 3: defining a global variable in the config adds a newline at the end of the string

Time:11-03

Vite 3 gives us the option to picture showing the output of the console.log

As you can see, there is a newline at the end of the string. This is unwanted and causes errors with tracking (it causes a mismatch on release versions).

It's also visible in the minified files:

picture showing the minified file with a newline in the middle

Is there any way to mitigate this, or should I find another way to access this variable?

CodePudding user response:

In your getReleaseVersion, you are using the the full output of running the command. This includes the trailing newline output by Git*.

To get the string you want, you will need to strip that trailing newline. For example:

const commitHash = childProcess
    .execSync('git rev-parse --short HEAD')
    .toString()
    .trim(); // This "removes the leading and trailing whitespace and line terminator characters from a string."

The reason the trim you are already doing does not work is that it is operating on the JSON-encoded string, so the first and last characters are double quotes and all newlines are escaped (e.g., ' foo\n' -> '" foo\\n"'). Thus, it does nothing.

* Almost all CLI programs output a trailing newline so that the terminal prompt is on a new line to the output.

  • Related