GithubHelp home page GithubHelp logo

iansan5653 / compress-tag Goto Github PK

View Code? Open in Web Editor NEW
14.0 1.0 2.0 655 KB

:abcd: Template literal tag for painless multiline strings in JS.

Home Page: https://www.npmjs.com/compress-tag

License: MIT License

TypeScript 100.00%
template-literals typescript whitespace formatting strings linebreaks newlines

compress-tag's Introduction

compress-tag

Image of code sample

compress-tag is a tiny module that enables significantly more readable code by improving the display of strings in your source code through the use of string template literals.

This module provides template literal tags that remove line breaks and indents from your template literals, so that a string that is formatted to nicely fit in your code still comes out looking like it should. They are also chainable in case you are already using template literal tags.

In other words, you can replace these workarounds:

throw new Error(
  "An error occured while parsing the CSV file. Check that the 'delimiters' option is set properly and try again."
);

const result = prompt(
  "Enter a description to attach to this entry. This should be " +
    "descriptive, but less than 200 characters.",
  "Enter your description here."
);

renderTextContent(`The quick brown fox jumps over the lazy dog. The \
quick brown fox jumps over the lazy dog. The quick brown fox jumps \
over the lazy dog. The quick brown fox jumps over the lazy dog. The \
quick brown fox jumps over the lazy dog.

The quick brown fox jumps over the lazy dog. The quick brown fox \
jumps over the lazy dog. The quick brown fox jumps over the lazy \
dog. The quick brown fox jumps over the lazy dog. The quick brown \
fox jumps over the lazy dog.`);

with these:

throw new Error(c`
  An error occured while parsing the CSV file. Check that the
  'delimiters' option is set properly and try again."
`);

const result = prompt(
  c`Enter a description to attach to this entry. This should be
    descriptive, but less than 200 characters.`,
  "Enter your description here."
);

renderTextContent(c`
  The quick brown fox jumps over the lazy dog. The quick brown fox
  jumps over the lazy dog. The quick brown fox jumps over the lazy
  dog. The quick brown fox jumps over the lazy dog. The quick brown
  fox jumps over the lazy dog.\n\n

  The quick brown fox jumps over the lazy dog. The quick brown fox
  jumps over the lazy dog. The quick brown fox jumps over the lazy
  dog. The quick brown fox jumps over the lazy dog. The quick brown
  fox jumps over the lazy dog.
`);

Getting Started

compress-tag is a UMD module, so it can be used in Node or on the web. Typings are included for TypeScript as well.

Usage in Node.JS

compress-tag is hosted on npm, so you can install with:

npm i compress-tag

To use in code:

import {c, t} from "compress-tag";

c`Example
  string.`; // => Example string.
t`Example
  string.`; // => Examplestring.

Documentation

Four template literal tag functions are exported by this module. compress and c are exactly the same - they replace your linebreaks and the whitespace surrounding each line with a single space. compressTight and t are also the same - they remove your linebreaks and whitespace with no space.

Examples

import {compress, c, compressTight, t} from "compress-tag";

// Use the regular compressor (preserves spaces) for prose:

let A = compress`Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Suspendisse  sagittis mi quam, ut rhoncus nisi pulvinar in. Duis
lobortis nisl libero, non imperdiet lectus ultrices sed. Aliquam erat
volutpat. Sed egestas dignissim iaculis. Etiam felis risus, tempor ac
dignissim id, vestibulum in mauris. Nam attempus tellus. Aliquam vitae
metus tempor, tempus tellus id, vulputate magna. Vivamus a enim
feugiat, mattis leo in, blandit nunc. Cras faucibus pellentesque
dolor, et euismod mauris sagittis vitae. Quisque egestas metus pretium
mollis tempor.`;
// => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sagittis mi quam, ut rhoncus nisi pulvinar in. Duis lobortis nisl libero, non imperdiet lectus ultrices sed. Aliquam erat volutpat. Sed egestas dignissim iaculis. Etiam felis risus, tempor ac dignissim id, vestibulum in mauris. Nam attempus tellus. Aliquam vitae metus tempor, tempus tellus id, vulputate magna. Vivamus a enim feugiat, mattis leo in, blandit nunc. Cras faucibus pellentesque dolor, et euismod mauris sagittis vitae. Quisque egestas metus pretium mollis tempor.

let B = c`Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Suspendisse sagittis mi quam, ut rhoncus nisi pulvinar in. Duis
lobortis nisl libero, non imperdiet lectus ultrices sed. Aliquam erat
volutpat. Sed egestas dignissim iaculis. Etiam felis risus, tempor ac
dignissim id, vestibulum in mauris. Nam attempus tellus. Aliquam vitae
metus tempor, tempus tellus id, vulputate magna. Vivamus a enim
feugiat, mattis leo in, blandit nunc. Cras faucibus pellentesque
dolor, et euismod mauris sagittis vitae. Quisque egestas metus pretium
mollis tempor.`;
// => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse sagittis mi quam, ut rhoncus nisi pulvinar in. Duis lobortis nisl libero, non imperdiet lectus ultrices sed. Aliquam erat volutpat. Sed egestas dignissim iaculis. Etiam felis risus, tempor ac dignissim id, vestibulum in mauris. Nam attempus tellus. Aliquam vitae metus tempor, tempus tellus id, vulputate magna. Vivamus a enim feugiat, mattis leo in, blandit nunc. Cras faucibus pellentesque dolor, et euismod mauris sagittis vitae. Quisque egestas metus pretium mollis tempor.

// Use the tight compressor (removes indentation) for code like HTML:

let C = compressTight`
  <section>
    <h1>Heading</h1>
    <p>This is the content of the section.</p>
    <p>This is another paragraph.</p>
  </section>
`;
// => <section><h1>Heading</h1><p>This is the content of the section.</p><p>This is another paragraph.</p></section>

let D = t`
  <section>
    <h1>Heading</h1>
    <p>This is the content of the section.</p>
    <p>This is another paragraph.</p>
  </section>
`;
// => <section><h1>Heading</h1><p>This is the content of the section.</p><p>This is another paragraph.</p></section>

Preserving Some Linebreaks / Whitespace

You can still output a string that has linebreaks and tabs in it simply by using the newline (\n) and tab (\t) characters. For example:

let E = c`This has\n\ta new line`;
// => This has
//     a new line.

Chaining

One drawback to using template literal tags is that they cannot be chained. This means that if you are already using template literal tags, you can't use these as described above. However, all of these tags support being used as normal functions in this case*:

// Assuming `capitalize` is some other tag that makes every letter uppercase:
let F = c(capitalize`
  Lorem ipsum
  dolor sit amet.
`);
// => LOREM IPSUM DOLOR SIT AMET.

* Note: When using tags as a method there is no way to preserve newlines; using the \n character will not work.

ESLint

Since there is now no reason for your strings to be long, you can modify your ESLint max-len setting to enforce the use of these tags:

eslintrc.json

{
  "rules": {
    "max-len": [
      "error",
      {
        "code": 80,
        "ignoreStrings": false,
        "ignoreTemplateLiterals": false
      }
    ]
  }
}

Contributing

Found a bug or want to see a feature added? Submit it here!

Pull requests are always welcome, although to increase your chances of your contribution being accepted, opening an issue and linking to it is always a good idea.

Pull requests will not be merged unless the Actions build succeeds. To quickly confirm that it will, just run:

npm run check

This checks your formatting, tests, and for TypeScript compiler errors. If the task doesn't fail, you should be good to go.

Other Tasks

For your convenience, some other tasks are also provided in the package.json:

  • npm run build - Compiles TypeScript code to JavaScript
  • npm run minify - Generate minified JavaScript files from compiled files
  • npm run test - Quickly run tests using TypeScript code without compiling
  • npm run lint - Check code for linting errors
  • npm run check - Check to ensure code will pass Pipelines checks (see above)
  • npm run format - Format code using Prettier

compress-tag's People

Contributors

dependabot[bot] avatar greenkeeper[bot] avatar iansan5653 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

compress-tag's Issues

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet.
We recommend using:

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

An in-range update of eslint-plugin-jsdoc is breaking the build 🚨

The devDependency eslint-plugin-jsdoc was updated from 18.1.2 to 18.1.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-jsdoc is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • Compile, Lint, and Test: #575 failed (Details).

Release Notes for v18.1.3

18.1.3 (2019-11-20)

Bug Fixes

  • newline-after-description: only treat comments with whitespace after two asterisks only as jsdoc (3d61126)
Commits

The new version differs by 1 commits.

  • 3d61126 fix(newline-after-description): only treat comments with whitespace after two asterisks only as jsdoc

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of prettier is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye 👋 and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


The devDependency prettier was updated from 2.0.3 to 2.0.4.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

prettier is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details

Release Notes for 2.0.4

🔗 Changelog

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Enable the manual preservation of newlines when using as wrappers

Currently, the following are treated the same when using the tags as wrappers instead of as template tags:

`This is a
test string.`
`This is a \ntest string.`

Previously, the workaround was to double escape the character, like so:

`This is a \\ntest string.`

However this causes problems with URIs:

`C:\\folder\\newfolder`

I'm open to other ideas. The reason it's possible with the normal tags is because the template literal tags have access to the .raw property of the passed string array, which allows the code to manually handle escape characters.

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.12.10 to 12.12.11.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Unicode escaped characters are not properly handled

Expected behavior:

c`\uD83D\uDE00`
// => "😀"

Actual behavior:

c`\uD83D\uDE00`
// => "\uD83D\uDE00"

Steps to fix:

  • Release the unraw module
  • Integrate unraw to replace existing code
  • Merge branch fix/unicode-escape-characters

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet.
We recommend using:

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

Keep line breaks, remove indentation

This is very handy, but it would be nice in some cases to have the option to preserve line breaks, but condense consecutive white-space characters after each line break. That would allow the creation of multi-line strings that are indented in the code, but not in the output.

function generateLetter() {
    return `Dear Sir or Madam,
                 
            We are writing to inform you that this example will clearly show that as of
            ${new Date().toLocaleString()} line breaks are preserved, but leading space from
            each line is stripped away.

            Sincerely,
            Us`;
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.