Babel plugin that compiles ES2015 unicode string and number literals to ES5
86
Create a Babel plugin that transforms source code by manipulating AST node metadata. The plugin should handle numeric and string literals by removing their original source representation metadata, allowing Babel's code generator to output normalized values.
Your plugin must:
Process Numeric Literals: Identify numeric literals that use non-standard prefixes (binary with 0b/0B prefix, octal with 0o/0O prefix) and remove their source metadata so they output as decimal numbers.
Process String Literals: Identify string literals containing unicode escape sequences (any string with \u in its raw representation) and remove their source metadata to allow normalized output.
Use Metadata Manipulation: Transform the AST by removing the metadata property that stores original source representations, rather than directly modifying node values.
Preserve Semantic Values: Ensure that the computed values of all literals remain unchanged - only the output format should change.
// Input
const a = 0b1010;
const b = 0B11111111;
// Output
const a = 10;
const b = 255;// Input
const perms = 0o755;
const other = 0O644;
// Output
const perms = 493;
const other = 420;// Input
const letter = "\u0041";
const emoji = "\u{1F600}";
// Output
const letter = "A";
const emoji = "😀";// Input
const binary = 0b111110111;
const octal = 0o767;
const hex = 0xFF; // Should NOT be transformed
const unicode = "\u0048\u0069";
// Output
const binary = 503;
const octal = 503;
const hex = 0xFF;
const unicode = "Hi";NumericLiteral and StringLiteral node typesCreate test cases in transform.test.js that verify:
// Input code
const x = 0b1010;
// Expected output after transformation
const x = 10;// Input code
const mode = 0o755;
// Expected output after transformation
const mode = 493;// Input code
const char = "\u0041\u0042";
// Expected output after transformation
const char = "AB";// Input code
const hex = 0xFF;
// Expected output after transformation (unchanged)
const hex = 0xFF;0x/0X prefix) should NOT be transformed as they are already ES5-compatible\u in the raw representation)Provides the core Babel transformation and AST traversal capabilities.
Provides the declare helper for creating Babel plugins with proper API versioning.
transform-literals-plugin.js - Your Babel plugin implementationtransform.test.js - Test suite validating all transformation scenariosInstall with Tessl CLI
npx tessl i tessl/npm-babel-plugin-transform-es2015-literalsdocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10