Extract comments from JS, JSX via js-tokens.
npm install extract-comments-es
yarn add extract-comments-es
pnpm add extract-comments-es
import { extractComments } from 'extract-comments-es'
const code = `
// This is foo
const foo = 'foo'
/**
* This is bar
*/
const bar = 'bar'
`
const result = extractComments(code)
console.log(result.comments)
- Type:
(code: string, options: ExtractOptions = {}) => ExtractResult
Extract comments from code. By default, it ignores HashbangComment
.
- Type:
(code: string) => ExtractComment[]
Shortcut to extract all comments.
- Type:
(code: string) => SingleLineComment[]
Shortcut to extract all single-line comments.
- Type:
(code: string) => MultiLineComment[]
Shortcut to extract all multi-line comments.
- Type:
(code: string) => HashbangComment[]
Shortcut to extract all hashbang comments.
export interface ExtractOptions {
/**
* Whether extract hashbang comments
*
* @default false
*/
hashbang?: boolean
/**
* Enable JSX support
*
* @default false
*/
jsx?: boolean
/**
* Whether extract multi-line comments
*
* @default true
*/
multiLine?: boolean
/**
* Whether extract single-line comments
*
* @default true
*/
singleLine?: boolean
}
type BaseComment<T extends JSXToken['type'] | Token['type']> = {
type: T
value: string
}
export type HashbangComment = BaseComment<'HashbangComment'>
export type MultiLineComment = BaseComment<'MultiLineComment'> & {
closed: boolean
}
export type SingleLineComment = BaseComment<'SingleLineComment'>
export type ExtractComment =
| HashbangComment
| MultiLineComment
| SingleLineComment
export interface ExtractResult {
comments: ExtractComment[]
hashbangComments: HashbangComment[]
multiLineComments: MultiLineComment[]
singleLineComments: SingleLineComment[]
}