Detect JSX in files and strings using AST analysis.
Detecting JSX isn't as simple as checking file extensions. JavaScript and TypeScript files (.js, .ts) can contain JSX syntax. This tool uses ast-grep's powerful AST parsing to reliably detect JSX node types from the JSX specification:
jsx_element- Standard tags:<div>...</div>jsx_self_closing_element- Self-closing:<Component />jsx_fragment- Fragments:<>...</>
npm install has-jsxUse the -f or --file flag to check files:
has-jsx -f src/Component.tsx
# Output: JSX detected
# Exit code: 0
has-jsx --file src/utils.ts
# Output: No JSX detected
# Exit code: 1Pass source code directly without any flags:
has-jsx "const App = () => <div>Hello</div>"
# Output: JSX detected
# Exit code: 0
has-jsx "const x = 5;"
# Output: No JSX detected
# Exit code: 1| Flag | Description |
|---|---|
-f, --file <path> |
Check a file for JSX |
--verbose |
Output results as JSON |
--quiet |
Silent mode, exit code only |
--version |
Show version number |
--help |
Show help |
| Code | Meaning |
|---|---|
0 |
JSX detected |
1 |
No JSX detected |
2 |
Error (file not found, read error, etc.) |
Check if a file contains JSX:
ESM (recommended):
import hasJSX from 'has-jsx';
const result = await hasJSX('src/Component.tsx');
console.log(result); // true or falseCommonJS:
const { hasJSX } = require('has-jsx');
(async () => {
const result = await hasJSX('src/Component.tsx');
console.log(result);
})();Check if a string contains JSX (synchronous, no file I/O):
ESM:
import { hasJSXInString } from 'has-jsx';
const code = `
function App() {
return <div>Hello World</div>;
}
`;
const result = hasJSXInString(code);
console.log(result); // trueCommonJS:
const { hasJSXInString } = require('has-jsx');
const code = 'const App = () => <div>Hello</div>';
const result = hasJSXInString(code);
console.log(result); // trueAnalyzes a file to detect JSX syntax.
Parameters:
filepath- Path to the file to analyze (relative or absolute)
Returns:
Promise<boolean>-trueif JSX is detected,falseotherwise
Throws:
Error- If file doesn't exist, is not a file, or can't be read
Example:
import hasJSX from 'has-jsx';
try {
const result = await hasJSX('src/Component.tsx');
if (result) {
console.log('This file contains JSX');
}
} catch (error) {
console.error('Error:', error.message);
}Analyzes a source code string to detect JSX syntax (synchronous).
Parameters:
source- Source code string to analyze
Returns:
boolean-trueif JSX is detected,falseotherwise
Throws:
TypeError- If source is not a string
Example:
import { hasJSXInString } from 'has-jsx';
const code = 'const Button = () => <button>Click</button>';
const result = hasJSXInString(code);
console.log(result); // true
// No false positives for TypeScript generics
const genericCode = 'function identity<T>(arg: T): T { return arg; }';
console.log(hasJSXInString(genericCode)); // false- Node.js >= 20.0.0
MIT
Issues and pull requests welcome! Please ensure all tests pass before submitting:
npm test