Blog
ts-dedent library in Storybook codebase.

ts-dedent library in Storybook codebase.

In this article, we review ts-dedent library in Storybook codebase. We will look at:

  1. What is ts-dedent?

  2. ts-dedent usage in Storybook codebase.

I study patterns used in an open source project found on Github Trending. For this week, I reviewed some parts of Storybook codebase and wrote this article.

What is ts-dedent?

ts-dedent is a TypeScript package which smartly trims and strips indentation from multi-line strings.

Usage Examples

import { dedent } from 'ts-dedent';

console.log(dedent`A string that gets so long you need to break it over
                    multiple lines. Luckily dedent is here to keep it
                    readable without lots of spaces ending up in the string
                    itself.`);
// or
console.log(dedent`
  A string that gets so long you need to break it over
  multiple lines. Luckily dedent is here to keep it
  readable without lots of spaces ending up in the string
  itself.
`);

results in

A string that gets so long you need to break it over
multiple lines. Luckily dedent is here to keep it
readable without lots of spaces ending up in the string
itself.

What would be result if you just used back ticks — ``? well, this dedent is not about line breaks but rather about indentation because of spaces. Below is an example that makes it easy to understand:

function example() {
  const message = `
    Hello,
    This is a message
    with multiple lines
  `;
  console.log(message);
}

This outputs with all the leading spaces preserved:

    Hello,
    This is a message
    with multiple lines

ts-dedent usage in Storybook codebase.

dedent is called at L40 in storybook/code/core/src/bin/loader.ts as shown below:

export function resolveWithExtension(importPath: string, currentFilePath: string): string {
  // If the import already has an extension, return it as-is
  if (path.extname(importPath)) {
    return importPath;
  }

  deprecate(dedent`One or more extensionless imports detected: "${importPath}" in file "${currentFilePath}".
    For maximum compatibility, you should add an explicit file extension to this import.
    Storybook will attempt to resolve it automatically, but this may change in the future.
    If adding the extension results in an error from TypeScript, we recommend setting moduleResolution to "bundler" in tsconfig.json
    or alternatively look into the allowImportingTsExtensions option.`);

About me:

Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.

Email: ramu.narasinga@gmail.com

Study the patterns used in large OSS projects at Think Throo.

References:

  1. https://github.com/storybookjs/storybook/blob/next/code/core/src/bin/loader.ts#L15

  2. https://github.com/tamino-martinius/node-ts-dedent