Strip Comments and Literals from JavaScript

3.1.0 · active · verified Sun Apr 19

strip-literal is a JavaScript utility library designed to remove comments and string literals from code while preserving character positions. This is achieved by replacing the stripped content with an equivalent number of spaces, which is crucial for maintaining source map integrity. The library is currently on version 3.1.0 and is actively maintained, with a recent focus on performance improvements. Key differentiators include its reliance on `js-tokens` for robust parsing and its commitment to preserving code structure for tools like linters or code transformers. The project has undergone significant breaking changes, notably transitioning to an ESM-only module in v3.0.0 and switching its internal parsing engine from `acorn` to `js-tokens` in v2.0.0. Releases are fairly regular, addressing bugs and introducing optimizations.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use `stripLiteral` to process JavaScript code, showcasing its behavior with various string and comment types while preserving whitespace for source map compatibility.

import { stripLiteral } from 'strip-literal';

// Example 1: Basic string literal stripping
const code1 = `const foo = 'hello world';\nconsole.log(foo);`;
const stripped1 = stripLiteral(code1);
console.log('Stripped 1:\n', stripped1);
// Expected: const foo = '           ';\nconsole.log(foo);

// Example 2: Template literal with interpolation and comments
const code2 = `
  const name = `Alice`; // This is a comment
  const greeting = `Hello, ${name}!`; /* multi-line
  comment */
  console.log(greeting);
`;
const stripped2 = stripLiteral(code2);
console.log('\nStripped 2:\n', stripped2);
/*
Expected Output:

  const name = `     `;             
  const greeting = `Hello, ${name}!`;            
  console.log(greeting);
*/

// Example 3: Stripping only specific types of literals (e.g., just comments)
// Note: The library strips all comments and string literals by default.
// For more granular control, you'd typically need a more advanced parser.
const code3 = `// Only comments please\nconst x = 1; /* another comment */`;
const stripped3 = stripLiteral(code3);
console.log('\nStripped 3:\n', stripped3);
// Expected:                  \nconst x = 1;                   

view raw JSON →