How to setup "Long" library for protobufjs as a NPM package

219 Views Asked by At

I'm building an Angular (Typescript) web application that uses Protobuf for communicating with other services. At first, we stored all .proto files in our project and used protobufjs to compile them into 2 files:

compiled.pb.js:

/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/
(function(global, factory) { /* global define, require, module */

    /* AMD */ if (typeof define === 'function' && define.amd)
        define(["protobufjs/minimal"], factory);

    /* CommonJS */ else if (typeof require === 'function' && typeof module === 'object' && module && module.exports)
        module.exports = factory(require("protobufjs/minimal"));

})(this, function($protobuf) {
    "use strict";

    var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util;
    
    var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {});
    
    $root.gng = (function() {

    // There are a lot more here...

complied.pb.d.ts:

import * as $protobuf from "protobufjs";
import Long = require("long");

Then setting up the Long library in another file in the project:

import * as Protobuf from 'protobufjs/minimal';
import * as Long from 'long';

// Enable Long number (e.g. timestamp in nano seconds) support in protobufjs
Protobuf.util.Long = Long;
Protobuf.configure();

Everything work fine, until we decide to move the all .proto files to a separate project and provide the compiled.pb.js and compiled.pb.d.ts via NPM (The content of the files is exactly the same as above)

enter image description here

Here is what's inside the package.json:

  "author": "",
  "dependencies": {
    "protobufjs": "^6.11.3"
  },
  "description": "",
  "keywords": [],
  "license": "ISC",
  "main": "compiled.pb.js",
  "name": "gh-proto",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "types": "./compiled.pb.d.ts",
  "version": "0.40.7"

Now we import the proto straight from the NPM package but have no way to initialize the Long library for it. I've tried to insert an index.js file as below, but it doesn't work:

import * as Protobuf from 'protobufjs/minimal';
import * as Long from 'long';

// Enable Long number (e.g. timestamp in nano seconds) support in protobufjs
Protobuf.util.Long = Long;
Protobuf.configure();
0

There are 0 best solutions below