js-tokens is a JavaScript tokenizer that leverages regular expressions to parse JavaScript code into a stream of tokens. It is known for its tiny footprint, lenient parsing approach, and robustness, designed to 'never fail' even on malformed input, making it suitable for tools that need to process potentially incomplete or invalid JavaScript. The current stable version is 10.0.0. While not strictly spec-compliant in all edge cases, its 'almost spec-compliant' nature makes it highly practical for tasks like syntax highlighting, basic static analysis, or code transformation where full AST parsing is overkill. It supports the latest ECMAScript features up to ES2025 and also offers an option for JSX support. The project maintains a steady release cadence for new ECMAScript features and bug fixes, with major versions often introducing changes to module formats or API surface to align with ecosystem shifts.
npm install js-tokensVerified import paths — ran on the pinned version, not inferred.
Demonstrates basic tokenization of a JavaScript string, extracting token values. Also shows enabling JSX support.
For CommonJS projects, use dynamic `import('js-tokens')` or ensure you are on Node.js 20.19.0 or later which supports `require(esm)`. For new projects, adopt `import` statements and ensure your project is configured for ESM.Update your code to call `jsTokens(string, options?)` and iterate over the returned generator function, rather than using a regex directly.
Ensure your environment runs Node.js 10 or newer. Review code that relies on specific token structures, names, or how whitespace was previously handled, and adjust to the updated specification-aligned token output.
For scenarios requiring absolute strict ECMAScript compliance, be aware of these limitations and consider a full-fledged AST parser. For most general-purpose tokenization (like syntax highlighting), `js-tokens`'s leniency is often an advantage.
Avoid processing extraordinarily large single tokens. For inputs with potential extreme length, consider pre-validation or chunking strategies if feasible.
For CommonJS projects, either enable `"type": "module"` in your `package.json` (requires Node.js 12+), or use dynamic `await import('js-tokens')`. For older Node.js versions or strict CommonJS, you might need Node.js 20.19.0+ to directly `require('js-tokens')`. Otherwise, refactor your project to use ES Modules.In CommonJS (for Node.js < 20.19.0 or without `"type": "module"`): use `const { default: jsTokens } = require("js-tokens");` or `const jsTokens = require("js-tokens").default;`. In ESM: ensure you use `import jsTokens from "js-tokens";`. For TypeScript, ensure `"esModuleInterop": true` in your `tsconfig.json`.No dependency data recorded yet.