Correctly generate code if package name is empty.

Fixes #306.
This commit is contained in:
Mitar 2018-10-04 21:25:13 -07:00 committed by Stanley Cheung
parent c727bcc6df
commit a312d85d38
1 changed files with 16 additions and 5 deletions

View File

@ -303,11 +303,12 @@ void PrintCommonJsMessagesDeps(Printer* printer, const FileDescriptor* file) {
string package = file->package();
vars["package_name"] = package;
printer->Print(vars, "const proto = {};\n");
if (!package.empty()) {
size_t offset = 0;
size_t dotIndex = package.find('.');
printer->Print(vars, "const proto = {};\n");
while (dotIndex != string::npos) {
vars["current_package_ns"] = package.substr(0, dotIndex);
printer->Print(vars, "proto.$current_package_ns$ = {};\n");
@ -325,9 +326,15 @@ void PrintCommonJsMessagesDeps(Printer* printer, const FileDescriptor* file) {
}
vars["filename"] = filename;
if (!package.empty()) {
printer->Print(
vars,
"proto.$package_name$ = require('./$filename$_pb.js');\n\n");
} else {
printer->Print(
vars,
"const proto = require('./$filename$_pb.js');\n\n");
}
}
void PrintES6Imports(Printer* printer, const FileDescriptor* file) {
@ -946,7 +953,11 @@ class GrpcCodeGenerator : public CodeGenerator {
printer.Print("}); // goog.scope\n\n");
break;
case ImportStyle::COMMONJS:
if (!vars["package"].empty()) {
printer.Print(vars, "module.exports = proto.$package$;\n\n");
} else {
printer.Print(vars, "module.exports = proto;\n\n");
}
break;
case ImportStyle::TYPESCRIPT:
break;