When working with JavaScript, TypeScript, and similar languages, you might need to strip out comments without altering the code structure. Here's a simple and effective way to do it using the GCC compiler.
gcc -fpreprocessed -E -P -x c - < in.js > out.js
Unlike tools like Babel or Prettier, this command doesn't parse the Abstract Syntax Tree (AST). Instead, it focuses solely on removing comments. This makes it particularly useful for handling unusual files, such as code snippets, which might otherwise cause errors due to invalid statements (like return outside of function bode), since the standard tools expect only whole files.
- No AST Parsing: Avoids the complexity and potential errors associated with AST parsing.
- Handles Unusual Files: Works with files that might have syntax issues or unconventional structures.
- Strips Blank Lines: Cleans up your code by removing unnecessary blank lines.
By using this command, you can efficiently clean your code, making it easier to read and maintain.
The raw GCC command still interprets lines starting with #
as preprocessor directives, including shebangs.
To bypass all lines starting with #
, you can use the following AWK script, which you can install with this command:
npm install -g https://gist.github.com/rindeal/067713ba639ed703f60a7c503afd55bb
# now you can run it like this:
#
# decomment-js < in.js > out.js
#