dmnd / dedent

⬅️ ES6 string tag that strips indentation from multi-line strings.
MIT License
931 stars 36 forks source link

Bug(?) JSON.serialize(..., null, 2) throws off indentation #78

Closed magicmark closed 1 year ago

magicmark commented 1 year ago

not sure if this is a bug or somehow expected behaviour that i don't understand yet, but here's a lil repro:

$ cat test.js 
const dedent = require('dedent');

console.log(
    dedent`
        Foo
        ${JSON.stringify({ a: 'b' }, null, 2)}
        Bar
    `,
);

$ node src/test.js 
Foo
      {
"a": "b"
}
      Bar

Observations:

thanks!

magicmark commented 1 year ago

fwiw this hack does what I want:

console.log(
    dedent`
        Foo
        ${JSON.stringify(JSON.stringify({ a: 'b' }, null, 2))
            .replace(/\\"/g, '"')
            .replace(/^"/, '')
            .replace(/"$/, '')}
        Bar
        Baz
        Qux
    `,
);

outputs:

$ node test.js
Foo
{
  "a": "b"
}
Bar
Baz
Qux
JoshuaKGoldberg commented 1 year ago

Interesting! The way template literal string work is by passing an array of strings and then the interpolated values to go in-between them:

const logArgs = (...args) => console.log(args);

logArgs`
  Foo
  ${JSON.stringify({ a: "b" }, null, 2)}
  Bar
`;
[
  [ '\n  Foo\n  ', '\n  Bar\n' ],
  '{\n  "a": "b"\n}'
]

I think this is a dup of #12, generally asking to dedent nested strings? Closing as such but please post back if I'm wrong. Thanks!