Removes leading indentation from ES6 template strings
ES6 template strings are great, but they preserve everything between the backticks, including leading spaces.
Sometimes I want to indent my template literals to make my code more readable without including all those spaces in the
string.
Outdent will remove those leading spaces, as well as the leading and trailing newlines.
Usage
Import outdent using your module system of choice.
// Denoimport outdent from 'http://deno.land/x/outdent/mod.ts';// ECMAScript modulesimport outdent from 'outdent';// CommonJSconst outdent = require('outdent');
Examples
import outdent from 'outdent';const markdown = outdent` # My Markdown File Here is some indented code: console.log("hello world!");`;console.log(markdown);fs.writeFileSync('output.md', markdown);
The contents of output.md do not have the leading indentation:
# My Markdown FileHere is some indented code: console.log("hello world!");
As a JavaScript string:
var markdown = '# My Markdown File\n' + '\n' + 'Here is some indented code:\n' + '\n' + ' console.log("hello world!");';
You can pass options to outdent to control its behavior. They are explained in Options.
You can explicitly specify the indentation level by passing outdent as the first interpolated value. Its position sets the indentation level and it is removed from the output:
Note: ${outdent} must be alone on its own line without anything before or after it. It cannot be preceded by any non-whitespace characters.If these conditions are not met, outdent will follow normal indentation-detection behavior.
Outdent can also remove indentation from plain strings via the string method.
Start the contents of your template string on a new line after the opening backtick. Otherwise, outdent
has no choice but to detect indentation from the second line, which does not work in all situations.
Spaces and tabs are treated identically. outdent does not verify that you are using spaces or tabs consistently; they
are all treated as a single character for the purpose of removing indentation. Spaces, tabs, and smart tabs should
all work correctly provided you use them consistently.
TypeScript declarations
This module includes TypeScript type declarations so you will get code completion and error-checking without installing anything else.