diff --git a/bin/pegjs b/bin/pegjs index e75de42..9c789a1 100755 --- a/bin/pegjs +++ b/bin/pegjs @@ -183,8 +183,8 @@ while (args.length > 0 && isOption(args[0])) { if (args.length === 0) { abort("Missing parameter of the --format option."); } - if (args[0] !== "amd" && args[0] !== "commonjs" && args[0] !== "globals" && args[0] !== "umd") { - abort("Module format must be one of \"amd\", \"commonjs\", \"globals\", and \"umd\"."); + if (args[0] !== "amd" && args[0] !== "commonjs" && args[0] !== "esm" && args[0] !== "globals" && args[0] !== "umd") { + abort("Module format must be one of \"amd\", \"commonjs\", \"esm\", \"globals\", and \"umd\"."); } options.format = args[0]; break; @@ -253,7 +253,7 @@ while (args.length > 0 && isOption(args[0])) { } if (Object.keys(options.dependencies).length > 0) { - if (options.format !== "amd" && options.format !== "commonjs" && options.format !== "umd") { + if (options.format !== "amd" && options.format !== "commonjs" && options.format !== "esm" && options.format !== "umd") { abort("Can't use the -d/--dependency option with the \"" + options.format + "\" module format."); } } diff --git a/lib/compiler/passes/generate-js.js b/lib/compiler/passes/generate-js.js index 4dd0295..a54494b 100644 --- a/lib/compiler/passes/generate-js.js +++ b/lib/compiler/passes/generate-js.js @@ -1227,6 +1227,23 @@ function generateJS(ast, options) { ].join("\n"); } + function generateParserExports() { + return options.trace + ? [ + "{", + " peg$SyntaxError as SyntaxError,", + " peg$DefaultTracer as DefaultTracer,", + " peg$parse as parse", + "}" + ].join("\n") + : [ + "{", + " peg$SyntaxError as SyntaxError,", + " peg$parse as parse", + "}" + ].join("\n"); + } + let generators = { bare() { return [ @@ -1273,6 +1290,36 @@ function generateJS(ast, options) { return parts.join("\n"); }, + esm() { + let parts = []; + let dependencyVars = Object.keys(options.dependencies); + + parts.push( + generateGeneratedByComment(), + "" + ); + + if (dependencyVars.length > 0) { + dependencyVars.forEach(variable => { + parts.push("import " + variable + + " from \"" + + js.stringEscape(options.dependencies[variable]) + + "\";" + ); + }); + parts.push(""); + } + + parts.push( + toplevelCode, + "", + "export " + generateParserExports() + ";", + "" + ); + + return parts.join("\n"); + }, + amd() { let dependencyVars = Object.keys(options.dependencies); let dependencyIds = dependencyVars.map(v => options.dependencies[v]);