Protobuf: Uncaught reference error: exports is not defined

Protobuf: Uncaught reference error: exports is not defined

我正在尝试将 protobuf 转换为打字稿中的 运行。

官方 Google 文档说简单地使用 npm install google-protobuf 然后到 require('google-protobuf').

我对 npm 没有经验,所以我 运行 遇到了几个问题。首先,require('google-protobuf')返回错误404,因为找不到文件。相反,我选择手动要求该文件,所以我在我的 index.html:

中获取了它
<script src="node_modules/google-protobuf/google-protobuf.js"></script>

这个应该工作正常吗? 相反发生的是我得到一个 Uncaught reference error: exports is not defined。我什至如何开始调试它?我试图查看 google-protobuf.js 文件并发现了一些 exports 语句,但我不知道我应该在这里做什么。

如果有帮助,这是我的 tsconfig.json 文件:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

您正在使用打字稿。尝试 import protobuf = reqquire('google-protobuf')

或通过 npm install @types/google-protobuf' 安装类型并将其包含在 import * as protobuf from 'google-protobuf'

HTML 中的 include 不起作用,因为 js 文件使用导入并且依赖项未解析。

如果你想在客户端使用它,你最终可以用 browserify 构建你的前端 js 文件。

首先,请确保您拥有合适的环境。我建议你:

  1. 安装and/or更新节点
  2. 安装and/or更新ts-node

然后,尝试以下解决方案:

JavaScript (ES5) + CommonJS

// test.js
var protobuf = require('google-protobuf');
console.log(protobuf);

运行 带有 node test.js 的脚本。

TypeScript + ES6 模块

// test.ts
import * as protobuf from 'google-protobuf';
console.log(protobuf);

运行 带有 ts-node test.ts 的脚本。

如果您在终端中看到一个常规对象,恭喜!该模块正在工作。但是现在,如果你想在你的浏览器中使用它,你将需要模块 loaders/bundlers 比如 BrowserifyWebpack...