count.macro icon indicating copy to clipboard operation
count.macro copied to clipboard

Babel macro for counting number of lines or words in files at compile time

count.macro

Babel
Macro

Count lines or words in files at build time

Installation

count.macro is a Babel macro. This will work out of the box with CRA, Gatsby, and Next.

npm install --save-dev count.macro

Usage

Line and word information is based on the source file, not the output file.

For example, this file

import { lines, linesIn, words, wordsIn } from "count.macro";

console.log(`This file has ${lines} lines`);
console.log(`lines.txt has ${linesIn("./lines.txt")}`);

console.log(`This file has ${words} words`);
console.log(`words.txt has ${wordsIn("./words.txt")}`);

will be transpiled to

console.log(`This file has ${7} lines`);
console.log(`lines.txt has ${100}`);
console.log(`This file has ${25} words`);
console.log(`words.txt has ${1000}`);

Named Exports

  • lines is a number that will be transpiled to number of lines in current file
  • linesIn is a function that takes a filename as an argument. The call will be replaced with the number of lines in the file (relative to the current file).
  • words is a number that will be transpiled to number of words in current file.
  • wordsIn is a function that takes a filename as an argument. The call will be replaced with the number of words in the file (relative to the current file).

CodeSandbox Example

Edit count.macro