cmtu - removing comments from code string has never been this easy.
Cmtu is a Node.js package that helps you easily remove, extract, and magic comments from code strings.
Built with TypeScript and has full type support.
Supports the most popular programming languages like Python, JavaScript, etc. out of the box.
Please consider following this project's author, Sina Bayandorian, and consider starring the project to show your :heart: and support.
Table of Contents
Install
Install with npm:
$ npm install --save cmtu
Usage
const cmtu = require('cmtu');
const jsCmtu = cmtu(cmtu.Languages.JS.resolver);
const jsCode = `
/*
this is a multi-line JS comment
*/
const callout = 'this is not a comment';
// this is a single line js comment
`;
const codeWithNoComments = jsCmtu.strip(jsCode);
console.log(codeWithNoComments, codeWithNoComments.length);
see built-in languages for a list of all built-in languages
API
returns a cmtu-object
configured based on the args passed to it.
Params
Returns
Example
const jsCmtu = cmtu(cmtu.Languages.JS.resolver);
const jsCode = `
/*
this is a multi-line JS comment
*/
const callout = '// this is not a comment';
// this is a single line js comment
`;
const { strip, extract, magic } = jsCmtu;
const comments = jsCmtu.extract(jsCode);
console.log(comments);
returns a cmtu-object
configured based on the args passed to it - the difference however is that methods exposed by this cmtu-object
are stringSensitive meaning that in the rare cases where your strings might include comments themselves, these methods can understand the difference. Take a look at the example below:
Params
Returns
Example
const jsCmtu = cmtu.stringSensitive(cmtu.Languages.JS.resolver);
const jsCode = `
/*
this is a multi-line JS comment
*/
const callout = '// this is not a comment';
// this is a single line js comment
`;
const { strip, extract, magic } = jsCmtu;
const codeWithNoComments = jsCmtu.strip(jsCode);
console.log(codeWithNoComments, codeWithNoComments.length);
Advanced Usage
you can customize cmtu to use it for languages that are not part of cmtu.Languages
by default, for example:
const pyCode = `
# this is a comment in python
callout = "// this is not a comment in python"
#! python comment to be excluded
`;
const pyResolver = '#.*';
const pyStringLiterals = ["'", '"', "'''", '"""'];
const pyCmtu = cmtu.stringSensitive(
pyResolver,
{
stringLiterals: pyStringLiterals,
exclude: [/#!.*/]
}
);
const { strip, extract, magic } = pyCmtu;
console.log(extract(pyCode));
console.log(strip(pyCode));
console.log(magic(pyCode));
Interfaces
type Resolver =
| string
| { block: string }
| { inline: string }
| { block: string; inline: string };
type LanguageName = 'JS' | 'CSS' | 'HTML' | 'CPP' | 'GO' | 'PYTHON' | 'PHP';
type Options = {
stringSensitive?: boolean;
stringLiterals?: string[];
exclude?: RegExp[];
};
{
strip: (code: string) => string;
extract: (code: string) => string[];
magic: (code: string) => [string, string[]];
}