protobuf.js icon indicating copy to clipboard operation
protobuf.js copied to clipboard

--target static-module --es6 --wrap es6 produces a code that fails to run

Open tkafka opened this issue 2 years ago • 5 comments
trafficstars

protobuf.js version: 7.2.5

Repro steps:

./node_modules/.bin/pbjs --target static-module --es6 --wrap es6 ./my-app.proto > ./js/my-app.js

Expected behavior: The generated code build and runs.

Actual behavior: Running the code results in error:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '<...>/node_modules/protobufjs/minimal' imported from <...>/protobuf/js/my-app.js

I need to replace

import * as $protobuf from "protobufjs/minimal"

// Common aliases
const $Reader = $protobuf.Reader, 
	$Writer = $protobuf.Writer,
	$util = $protobuf.util

// Exported root namespace
const $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {})

for

import * as $protobuf from "protobufjs/minimal.js"; // added .js

// Common aliases
const $Reader = $protobuf.default.Reader, // replaced $protobuf with $protobuf.default
	$Writer = $protobuf.default.Writer,
	$util = $protobuf.default.util

// Exported root namespace
const $root = $protobuf.default.roots || ($protobuf.default.roots = {}) // replaced $protobuf.roots["default"] with $protobuf.default.roots

... in order to make the generated module runnable.

Possible related: https://github.com/protobufjs/protobuf.js/issues/1862

tkafka avatar Aug 25 '23 10:08 tkafka

Providing a custom fixed dependency name and wrapper according to this post works, but ES6 module generation should work out of the box.

tkafka avatar Aug 25 '23 11:08 tkafka

protobuf only exports minimal as commonjs. It would be neat to publish a module version as well.

See here: https://www.typescriptlang.org/docs/handbook/esm-node.html https://nodejs.org/api/packages.html#conditional-exports

jolting avatar Sep 02 '23 00:09 jolting

It works. Replace $protobuf with $protobuf.default

/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/
import * as $protobuf from "protobufjs/minimal.js";

// Common aliases
const $Reader = $protobuf.default.Reader, $Writer = $protobuf.default.Writer, $util = $protobuf.default.util;

// Exported root namespace
const $root = $protobuf.default.roots["default"] || ($protobuf.default.roots["default"] = {});

......

Yiiip avatar Jun 07 '24 08:06 Yiiip