使用库时出现“Uncaught: ReferenceError: process is not defined”错误。

3

这是完整的错误信息

Uncaught ReferenceError: process is not defined
    at index.js:34
    at Object../node_modules/utp/index.js (index.js:41)
    at Object.options.factory (react refresh:6)
    at __webpack_require__ (bootstrap:24)
    at fn (hot module replacement:61)
    at Object../node_modules/peer-wire-swarm/index.js (index.js:1)
    at Object.options.factory (react refresh:6)
    at __webpack_require__ (bootstrap:24)
    at fn (hot module replacement:61)
    at Object../node_modules/torrent-stream/index.js (index.js:2)

此项目是使用npx create-react-app创建的,并通过react-scripts start命令启动。 这是App.js文件。

import torrentStream from "torrent-stream";

function App() {
  return (
    <h1>Hello World</h1>
  );
}

export default App;

当我删除第一行import torrentStream from "torrent-stream";时,一切正常。

我尝试安装react-error-overlay但没有效果。像这样在webpack中添加新的插件:

new webpack.DefinePlugin({
    process: {env: {}}
}),

将错误更改为:

Uncaught TypeError: {(intermediate value)}.hrtime is not a function
    at index.js:34
    at Object.../../node_modules/utp/index.js (index.js:41)
    at Object.options.factory (react refresh:6)
    at __webpack_require__ (bootstrap:24)
    at fn (hot module replacement:61)
    at Object../node_modules/peer-wire-swarm/index.js (index.js:1)
    at Object.options.factory (react refresh:6)
    at __webpack_require__ (bootstrap:24)
    at fn (hot module replacement:61)
    at Object../node_modules/torrent-stream/index.js (index.js:2)

我尝试过以下解决方案:解决方案1解决方案2解决方案3解决方案4,但都没有起到任何帮助作用。 我更改了webpack配置,在config.resolve中添加了此回退。
fallback: {
        "stream": require.resolve("stream-browserify"),
        "path": require.resolve("path-browserify"),
        "crypto": require.resolve("crypto-browserify"),
        "os": require.resolve("os-browserify/browser"),
        "tty": require.resolve("tty-browserify"),
        "https": require.resolve("https-browserify"),
        "http": require.resolve("stream-http"),
        "zlib": require.resolve("browserify-zlib"),
        "constants": require.resolve("constants-browserify"),
        "fs": false,
        "dgram": false,
        "dns": require.resolve("dns"),
        "process": false
      },

torrent-stream是一个用于Node.js的模块(其中process是预定义的全局变量),但您正在尝试在浏览器中使用它。这是行不通的。不幸的是,现在很容易混淆,因为既设计用于Node.js的模块,也设计用于浏览器的模块(或两者都可以使用)都在npm中(以前只有Node.js的东西,但然后打包程序开始提供从node_modules捆绑事物的能力,水变得非常混乱)。 - T.J. Crowder
那么有没有办法使用该模块,将来我如何知道该模块是用于在Node.js还是浏览器中使用的? - poseg46790
我不知道所涉及的模块,但如果它正在使用 process,那么不能在浏览器中使用。我不知道是否有一种通用的方法来确定您是否可以在浏览器中使用 npm 模块,除非根据我的经验,如果它没有明确说明是针对浏览器的并且没有清晰的基于浏览器的示例,那么它可能不适用于浏览器。 - T.J. Crowder
1个回答

1

我曾经遇到这个问题很长时间,现在我将分享我的问题/解决方案。

由于该项目由多个开发人员开发,有些开发人员使用NPM,而其他人使用YARN。此外,一个开发人员安装的包是NPM包,而另一个开发人员(我)不知道这一点,所以我运行npm run start,但是包是使用YARN安装的。

提示:确保您只使用NPM或YARN,并且您node_modules文件夹中的包是由您使用的软件包管理器生成的。


我因为在一个npm项目上错误地执行了yarn upgrade而被卡住了,谢谢! - Álvaro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接