【问题标题】:Protobuf: Uncaught reference error: exports is not definedProtobuf:未捕获的引用错误:未定义导出
【发布时间】:2017-11-01 09:34:58
【问题描述】:

我正在尝试让 protobuf 在 typescript 中运行。

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"
  ]
}

【问题讨论】:

  • 您实际上需要“google-protobuf”。在需要它时,您不应该收到 404 错误。你应该试着把你的精力集中在那里。

标签: javascript typescript npm protocol-buffers


【解决方案1】:

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

  1. 安装和/或更新节点
  2. 安装和/或更新 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 运行脚本。

如果您在终端中看到常规对象,恭喜!该模块正在工作。但是现在,如果你想在浏览器中使用它,你将需要像 BrowserifyWebpack 这样的模块加载器/捆绑器...

【讨论】:

    【解决方案2】:

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

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

    HTML中的include不起作用,因为js文件使用了import,并且依赖没有解析。

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

    【讨论】:

      猜你喜欢
      • 2013-10-27
      • 2011-09-25
      • 2021-11-01
      • 2017-11-22
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多