Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stripIndent not stripping 1st line of variables #208

Open
latipun7 opened this issue Sep 29, 2020 · 1 comment
Open

stripIndent not stripping 1st line of variables #208

latipun7 opened this issue Sep 29, 2020 · 1 comment

Comments

@latipun7
Copy link

I have this line of code:
code

but, the 1st line of variables that contain their line break and indent not stripped at 1st line, it takes the 8 spaces indent from the code. (sorry if the description not very descriptive or hard to understand)

the result is like this:
console.log(JSON.stringify(meta, null, 2)) :

{
  "code": "ERR_INVALID_ARG_TYPE"
}

console.log(stack) :

TypeError [ERR_INVALID_ARG_TYPE]: Error msg
    at stackTrace (internal/validators.js:122:11)
    ...etc

but this is the result of the stripIndent of them:

Variable that contain "\n    " would not strip for their 1st line below this.
        {
  "code": "ERR_INVALID_ARG_TYPE"
}
        TypeError [ERR_INVALID_ARG_TYPE]: Error msg
    at validateString (internal/validators.js:122:11)
    ...etc

notice the difference. Their 1st line not stripped. They take 8 spaces, same as the code.

@ryan953
Copy link

ryan953 commented Oct 13, 2020

I had the same issue too, but I was able to get around it.
I was doing something like:

// broken
function foo() {
  const content = JSON.stringify({name: "foo"}, null, "\n");

  return stripIndent`
    Head 1
    Head 2
    ${content}
  `;
}
console.log(foo());

And I expected it to return (no leading whitespace):

Head 1
Head 2
{
  "name": "foo"
}

But instead it was returning this (leading whitespace on line 2):

Head 1
    Head 2
{
  "name": "foo"
}

The problem was that stripIndent was getting a string that had the content variable already expanded. The closing } in my json had zero indentation.
It was as if I wrote:

function foo() {
  return stripIndent`
    Head 1
    Head 2
    {
  "name": "foo"
}";
  `;
}

I solved the problem by first stripping the header text, then concat the json after:

// Fixed!
function foo() {
  const content = JSON.stringify({name: "foo"}, null, "\n");

  return stripIndent`
    Head 1
    Head 2
  ` + '\n' + content;
}
console.log(foo());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants