javascript-obfuscator-lite
v1.0.4
Published
A lightweight, AST-based JavaScript obfuscator with a CLI, an API, Webpack/Rollup/Vite plugins, and opt-in source maps.
Maintainers
Readme
javascript-obfuscator-lite
Website: https://js-obfuscator.github.io
A lightweight, AST-based JavaScript obfuscator with a friendly CLI, a programmatic API, and Webpack, Rollup, and Vite plugins. It rewrites JavaScript into code that is harder for humans to read while preserving the original runtime behavior.
For stronger obfuscation, use the full professional suite at https://www.js-obfuscator.com
Features
- String protection — string arrays, reversal expressions, and Unicode escaping.
- Expression protection — hexadecimal property access, XOR-encoded numbers, wrapped binary expressions, encoded booleans, and junk assignments.
- Code-shape protection — zombie declarations and switch-based control-flow flattening.
- Identifier renaming — configurable global/local renaming with collision-safe, file-wide unique names.
- Optional eval encoding — opt-in
eval(String.fromCharCode(...))expression encoding. - Safety checks — exported names, CommonJS globals, JSX, module specifiers,
class/object keys, destructuring, and
withstatements are handled conservatively. - CLI + API — file, stdin/stdout, JSON-style options, TypeScript type definitions, and zero configuration to get started.
- Bundler plugins — Webpack 5, Rollup, and Vite plugins for obfuscating emitted production chunks.
- Source maps — opt-in source maps for the API, CLI, and bundler plugins.
Requirements
- Node.js 12 or newer.
- The obfuscator runs in Node.js. The generated JavaScript can target any runtime that supports the syntax used by the input.
Installation
Install it as a project dependency:
npm install --save-dev javascript-obfuscator-liteOr run it without installing:
npx javascript-obfuscator-lite --helpQuick start
CLI
npx javascript-obfuscator-lite input.js -o output.js
node output.jsUse - for stdin or stdout:
cat input.js | npx javascript-obfuscator-lite - > output.js
npx javascript-obfuscator-lite input.js --quiet | nodeProgrammatic API
CommonJS:
const fs = require('node:fs');
const { obfuscate } = require('javascript-obfuscator-lite');
const source = fs.readFileSync('input.js', 'utf8');
const output = obfuscate(source, {
controlFlow: true,
stringArray: true,
});
fs.writeFileSync('output.js', output);ES modules:
import { readFileSync, writeFileSync } from 'node:fs';
import { obfuscate } from 'javascript-obfuscator-lite';
const output = obfuscate(readFileSync('input.js', 'utf8'), {
renameGlobals: false,
});
writeFileSync('output.js', output);Obfuscate a file directly:
const { obfuscateFile } = require('javascript-obfuscator-lite');
obfuscateFile('src/app.js', 'dist/app.js', {
compact: true,
});CLI reference
Usage: javascript-obfuscator-lite [options] <input> [output]
Arguments:
input Input file, or "-" for stdin
output Output file, or "-" for stdout (default: "-")
Options:
-o, --output <file> Write output to <file>
-c, --compact Emit compact code
-k, --comments Preserve comments
--parser-plugins <p> Comma-separated Babel parser plugins (e.g. jsx)
--eval Enable eval-based expression encoding
--no-string-array Disable the string array transform
--no-string-reverse Disable string reversal
--no-string-unicode Disable unicode string escaping
--no-member-expression
Disable computed property encoding
--no-numeric-literal Disable numeric literal encoding
--no-binary-expression
Disable binary expression wrapping
--no-boolean-literal Disable boolean literal encoding
--no-assignment-junk Disable assignment junk code
--no-zombie-code Disable zombie code injection
--no-control-flow Disable control-flow flattening
--no-rename-globals Keep top-level variable/function names
--no-rename-locals Keep function-scoped names
--source-map Write a .map file next to the output file
--source-map-inline Embed the source map as a data URI
-q, --quiet Suppress banner and status messages
--verbose Print diagnostic details to stderr
-h, --help Show this help
-v, --version Show the versionThe positive forms of the transform flags are accepted too, for example
--string-array or --rename-globals. For long flags, the last occurrence
wins.
CLI examples
Obfuscate a single file with the defaults:
npx javascript-obfuscator-lite src/app.js -o dist/app.jsUse a compact build and keep license comments:
npx javascript-obfuscator-lite -c -k src/app.js -o dist/app.jsTurn off the most invasive transforms:
npx javascript-obfuscator-lite \
--no-control-flow \
--no-rename-globals \
--no-zombie-code \
src/app.js -o dist/app.jsProcess JSX:
npx javascript-obfuscator-lite --parser-plugins jsx src/App.jsx -o dist/App.jsWrite an external source map:
npx javascript-obfuscator-lite src/app.js -o dist/app.js --source-mapThis writes dist/app.js.map and appends a sourceMappingURL comment.
--source-map requires a file output.
Embed an inline source map:
npx javascript-obfuscator-lite src/app.js -o dist/app.js --source-map-inline--source-map-inline also works when writing to stdout:
cat src/app.js | npx javascript-obfuscator-lite --source-map-inline - > dist/app.jsExit codes
0— success.1— invalid arguments, I/O error, parse error, or obfuscation error.
Status messages and the banner are written to stderr, so stdout contains
only generated code. Use --quiet to suppress all non-error output.
API reference
obfuscate(source, options?)
Returns the obfuscated code as a string.
const { obfuscate } = require('javascript-obfuscator-lite');
const output = obfuscate('console.log("hello");', {
stringArray: false,
compact: true,
});| Parameter | Type | Description |
| --- | --- | --- |
| source | string | JavaScript source code. A leading BOM is removed. |
| options | object | Optional overrides for the defaults. |
Throws TypeError for non-string input or invalid options, and SyntaxError
for invalid JavaScript.
obfuscateWithSourceMap(source, options?, mapOptions?)
Obfuscates source code and returns both the generated code and a standard source map v3 object:
const fs = require('fs');
const { obfuscateWithSourceMap } = require('javascript-obfuscator-lite');
const { code, map } = obfuscateWithSourceMap(source, { compact: true }, {
sourceFileName: 'src/app.js',
file: 'dist/app.js'
});
fs.writeFileSync(
'dist/app.js',
`${code}\n//# sourceMappingURL=app.js.map\n`
);
fs.writeFileSync('dist/app.js.map', JSON.stringify(map));| Map option | Type | Description |
| --- | --- | --- |
| sourceFileName | string | Original source name in the map. Defaults to input.js. |
| sourceRoot | string | Optional sourceRoot value written to the map. |
| file | string | Generated file name written to the map. |
The returned map includes sourcesContent, so the original source is embedded
in the map. Source maps are opt-in and expose the original source code.
obfuscateFile(inputPath, outputPath?, options?)
Reads a file, obfuscates it, and optionally writes the result. Parent directories for the output are created automatically. Returns the generated code.
// Write the result.
obfuscateFile('input.js', 'dist/output.js', { compact: true });
// Only return the result.
const code = obfuscateFile('input.js', { compact: true });normalizeOptions(options?)
Validates options, applies aliases, and fills in defaults.
const { normalizeOptions } = require('javascript-obfuscator-lite');
const options = normalizeOptions({ string_array: false });
// { stringArray: false, ...all other defaults }defaultOptions
A frozen object containing every default value.
const { defaultOptions } = require('javascript-obfuscator-lite');
console.log(defaultOptions.eval); // falseversion
The installed package version.
const { version } = require('javascript-obfuscator-lite');
console.log(version);Bundler plugins
javascript-obfuscator-lite ships with Webpack, Rollup, and Vite plugins. They
obfuscate emitted JavaScript chunks and assets in production builds.
Complete option set
Define the options once and reuse the same object in every plugin config:
// Balanced preset: every option is explicit.
const obfuscatorOptions = {
// String protection.
stringArray: true,
stringReverse: true,
stringUnicode: true,
// Expression and property protection.
memberExpression: true,
numericLiteral: true,
binaryExpression: true,
booleanLiteral: true,
assignmentJunk: true,
// Code-shape protection.
zombieCode: true,
controlFlow: false,
// Opt-in: requires eval support and may conflict with CSP.
eval: false,
// Rename locals, but keep the public global API stable.
renameGlobals: false,
renameLocals: true,
// Output formatting.
compact: false,
comments: false,
// Babel parser plugins, for example: ['jsx'].
parserPlugins: []
};Every option is optional and accepts the same values as the API and CLI. The defaults apply when an option is omitted.
Webpack
const JavaScriptObfuscatorLitePlugin = require('javascript-obfuscator-lite/webpack');
module.exports = {
plugins: [
new JavaScriptObfuscatorLitePlugin({
include: /\.(?:m?js|cjs)$/i,
exclude: /vendor/,
sourceMap: true,
options: obfuscatorOptions
})
]
};Webpack 5 or newer is required. The plugin runs during the asset optimization
stage and processes matching .js, .mjs, and .cjs assets.
Rollup
import JavaScriptObfuscatorLitePlugin from 'javascript-obfuscator-lite/rollup';
export default {
plugins: [
JavaScriptObfuscatorLitePlugin({
include: /\.(?:m?js|cjs)$/i,
exclude: /vendor/,
sourceMap: true,
options: obfuscatorOptions
})
]
};Vite
import { defineConfig } from 'vite';
import JavaScriptObfuscatorLitePlugin from 'javascript-obfuscator-lite/vite';
export default defineConfig({
plugins: [
JavaScriptObfuscatorLitePlugin({
include: /\.(?:m?js|cjs)$/i,
exclude: /vendor/,
sourceMap: true,
options: obfuscatorOptions
})
]
});The Vite plugin runs only for production builds. By default it skips SSR
output; set ssr: true to obfuscate SSR chunks too.
Plugin options
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| include | RegExp | string | function | array | /\.(?:m?js\|cjs)$/i | Chunk or asset names to process. A string is matched as a substring. |
| exclude | RegExp | string | function | array | undefined | Chunk or asset names to skip. |
| options | object | {} | Obfuscator options passed to obfuscate(). |
| sourceMap | boolean | false | Emit a source map for each obfuscated chunk/asset. |
| ssr | boolean | false | Vite only: also process SSR output. |
Plugin notes
- Set
sourceMap: trueto emit maps. With the defaultfalse, source maps are removed, including.mapassets andsourceMappingURLcomments. - Plugin maps point back to the emitted chunk or asset received by the plugin; they are not composed with the bundler's earlier module-level maps.
- Obfuscation is randomized; plugin builds are not byte-for-byte reproducible.
- Disable
evalwhen the target page uses a strict Content Security Policy. - Use
parserPlugins: ['jsx']when bundling JSX that has not been fully transpiled before the plugin runs. - Plugin packages are loaded through subpath exports:
require('javascript-obfuscator-lite/webpack');
require('javascript-obfuscator-lite/rollup');
require('javascript-obfuscator-lite/vite');Options
All options are optional. The defaults are aggressive, with one deliberate
exception: the eval transform is disabled by default.
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| stringArray | boolean | true | Move string literals into a file-level array and reference them by index. |
| stringReverse | boolean | true | Replace strings with reverse/split/join expressions. Strings containing surrogate pairs are skipped. |
| stringUnicode | boolean | true | Escape string literals as \uXXXX sequences, including valid surrogate pairs. |
| memberExpression | boolean | true | Convert object.property to object['\x...']. |
| numericLiteral | boolean | true | Replace small integer literals with XOR expressions. |
| binaryExpression | boolean | true | Wrap binary variable initializers in an IIFE call. |
| booleanLiteral | boolean | true | Replace booleans with !![] / ![]. |
| assignmentJunk | boolean | true | Wrap literal assignment values in an IIFE. |
| zombieCode | boolean | true | Insert dead variable declarations and assignments. |
| controlFlow | boolean | true | Flatten eligible function bodies into switch-based dispatchers. |
| eval | boolean | false | Encode expressions with eval(String.fromCharCode(...)). |
| renameGlobals | boolean | true | Rename top-level variables and functions. |
| renameLocals | boolean | true | Rename function-scoped variables and functions. |
| compact | boolean | false | Emit compact output. |
| comments | boolean | false | Preserve comments. |
| parserPlugins | string[] | [] | Extra Babel parser plugins, for example ['jsx']. |
parserPlugins is a parser setting, not an obfuscation switch. It tells Babel
which non-default syntax to accept before the transforms run. Use [] for
standard JavaScript, ['jsx'] for JSX, and ['importAttributes'] for import
attributes. TypeScript, Flow, and ESTree are rejected; transpile them to
JavaScript first.
Example configuration
const { obfuscate } = require('javascript-obfuscator-lite');
const output = obfuscate(source, {
// Strong string and expression protection.
stringArray: true,
stringReverse: true,
stringUnicode: true,
memberExpression: true,
numericLiteral: true,
binaryExpression: true,
booleanLiteral: true,
assignmentJunk: true,
// Code-shape protection.
zombieCode: true,
controlFlow: true,
// Rename local names but keep the public global API stable.
renameGlobals: false,
renameLocals: true,
// Do not require eval at runtime.
eval: false,
// Readable output for debugging.
compact: false,
comments: true,
});What it does
The obfuscator parses source with Babel, applies AST transforms, and generates JavaScript again. It does not execute the input and does not send source code anywhere.
Transform order:
- String reversal
- Zombie declarations
- Member-expression encoding
- Assignment junk
- Numeric literal encoding
- Binary expression wrapping
- Boolean literal encoding
- Unicode string escaping
- Control-flow flattening
- String array construction
- Identifier renaming
- Eval encoding (only when
eval: true)
Illustrative input:
function greet(name) {
const greeting = "Hello, ";
return greeting + name + "!";
}
console.log(greet("World"));Illustrative output (actual output is randomized):
var _0 = ["Hello, ", "!", "log"];
function _1(name) {
var _3 = _0[0];
return _3 + name + _0[1];
}
console[_0[2]](_1("World"));Safety and limitations
Obfuscation is not encryption
Obfuscation raises the cost of reading and copying code. It cannot make code impossible to recover, and it is not a place to hide secrets, API keys, or credentials. Anything shipped to a client can eventually be inspected.
Global renaming can break external references
renameGlobals is enabled by default. It can break code that is accessed from
outside the obfuscated file, including:
- other scripts that read
window.someNameorglobalThis.someName; - inline HTML event handlers;
- names referenced from
eval("...")ornew Function("...")strings; - string-based global lookups.
Exported ES module bindings and CommonJS export patterns are detected automatically and protected from global renaming. For libraries, browser globals, or code that must keep a stable top-level API, disable global renaming:
npx javascript-obfuscator-lite --no-rename-globals input.js -o output.jsLocal renaming can also affect code that inspects function names, stack traces,
or Function.prototype.toString(). This is expected for obfuscation.
eval is opt-in
The eval transform is disabled by default because:
- it requires
evalto be allowed (for example, strict Content Security Policy configurations often block it); - it is slower at runtime;
- it produces larger output.
Enable it explicitly:
npx javascript-obfuscator-lite --eval input.js -o output.jsIt is skipped in strict-mode code, ES modules, class bodies, with statements,
and scopes where eval or String is shadowed. It is not a security boundary.
Dynamic code and with
Code that relies on dynamic name resolution can be incompatible with renaming.
This includes eval("variableName"), new Function("return variableName"), and
similar patterns. Disable renameGlobals/renameLocals for such code.
When a with statement is present, the obfuscator skips zombie code,
control-flow flattening, string arrays, and renaming for that file. The other
transforms still apply.
TypeScript and Flow
TypeScript and Flow syntax are not supported. Transpile to JavaScript first
(for example with tsc, esbuild, or Babel) and then obfuscate the output.
Passing the typescript, flow, or estree parser plugin is rejected with a
clear error.
JSX
JSX is supported when the parser plugin is enabled:
obfuscate(source, { parserPlugins: ['jsx'] });npx javascript-obfuscator-lite --parser-plugins jsx src/App.jsx -o dist/App.jsJSX attribute strings are preserved as raw text. JSX component names are
renamed consistently with their bindings. The obfuscator parses and emits JSX
as-is; it does not convert JSX to React.createElement. Keep your normal JSX
transpilation step in the build pipeline, or transpile JSX before obfuscating.
Import attributes
Use the importAttributes parser plugin. Generated code uses the modern
with { ... } attribute syntax, so make sure the target runtime supports it.
Randomized output
Names, XOR keys, control-flow layout, and other details are randomized on every run. Two runs on the same input will produce different files. This is useful for builds, but means output is not byte-for-byte reproducible.
Output size and performance
Control-flow flattening and zombie code increase output size and can add a small runtime cost. Disable them for size-sensitive bundles:
npx javascript-obfuscator-lite --no-control-flow --no-zombie-code input.js -o output.jsSource maps are opt-in through obfuscateWithSourceMap(), --source-map,
--source-map-inline, or the bundler plugin's sourceMap: true option. They
are disabled by default. Comments are removed unless comments: true /
--comments is used, so keep license headers with --comments.
License
MIT © 2026 Wang Yinzhen
Acknowledgements
Built with Babel for parsing, AST traversal, code generation, and types.
