From 9fceaa69667895e609a3ed78eb2efa7a0ecfb890 Mon Sep 17 00:00:00 2001 From: Rob Moran Date: Fri, 18 May 2018 12:42:08 +0100 Subject: [PATCH] CLI: Added an option to pbts to allow custom imports (#1038) --- cli/pbts.js | 38 +++++++++++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/cli/pbts.js b/cli/pbts.js index 7a63f1cca..ec62319d5 100644 --- a/cli/pbts.js +++ b/cli/pbts.js @@ -24,9 +24,10 @@ exports.main = function(args, callback) { name: "n", out : "o", main: "m", - global: "g" + global: "g", + import: "i" }, - string: [ "name", "out", "global" ], + string: [ "name", "out", "global", "import" ], boolean: [ "comments", "main" ], default: { comments: true, @@ -49,6 +50,8 @@ exports.main = function(args, callback) { "", " -g, --global Name of the global object in browser environments, if any.", "", + " -i, --import Comma delimited list of imports. Local names will equal camelCase of the basename.", + "", " --no-comments Does not output any JSDoc comments.", "", chalk.bold.gray(" Internal flags:"), @@ -135,6 +138,13 @@ exports.main = function(args, callback) { return undefined; }); + function getImportName(importItem) { + var result = path.basename(importItem, ".js") + return result.replace(/([-_~.+]\w)/g, match => { + return match[1].toUpperCase(); + }); + } + function finish() { var output = []; if (argv.global) @@ -142,11 +152,25 @@ exports.main = function(args, callback) { "export as namespace " + argv.global + ";", "" ); - if (!argv.main) - output.push( - "import * as $protobuf from \"protobufjs\";", - "" - ); + + if (!argv.main) { + // Ensure we have a usable array of imports + var importArray = typeof argv.import === "string" ? argv.import.split(",") : argv.import || []; + + // Build an object of imports and paths + var imports = { + $protobuf: "protobufjs" + }; + importArray.forEach(function(importItem) { + imports[getImportName(importItem)] = importItem; + }); + + // Write out the imports + Object.keys(imports).forEach(function(key) { + output.push("import * as " + key + " from \"" + imports[key] + "\";"); + }); + } + output = output.join("\n") + "\n" + out.join(""); try {