微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试将 npm 与 CodeSandbox 结合使用时,为什么会出现“无法解析‘http’”错误?

如何解决尝试将 npm 与 CodeSandbox 结合使用时,为什么会出现“无法解析‘http’”错误?

我是一名初级编码员,正在尝试学习如何使用 npm,特别是 webpack 和 CodeSandBox。我想把我做的一个项目放到一个在线代码编辑器上。 Repl.it 给我带来了麻烦,其他人说他们使用 CodeSandBox,所以我想我会尝试。

我的项目在这里https://github.com/acchang/ProjectToDoList 这是 GitHub 页面上的样子:https://acchang.github.io/ProjectToDoList/

我注意到 CodeSandBox 提供了可能用于此目的的称为容器的东西。我使用了 Node HTTP server 模板。我想我会在做任何其他事情之前尝试构建 webpack“基本设置”。

这些说明在这里https://webpack.js.org/guides/getting-started/#using-a-configuration

(编辑:但我后来了解到这甚至可能不是我所处的正确环境!我不知道如何为服务器编码。我的代码旨在通过浏览器运行,所以Node HTTP server 模板甚至可能不是正确的策略。)

CodeSandBox 中的终端按我的预期工作。它允许我使用终端并安装 npm。在 VSCode 中,如果我在 index.js 中使用此代码,所有这些步骤将在浏览器中以文本“Hello webpack”结束:

import _ from "lodash";

function component() {
  const element = document.createElement("div");
  element.innerHTML = _.join(["Hello","webpack"]," ");
  return element;
}

document.body.appendChild(component());

但是,在使用 CodeSandBox 尝试相同操作时,我收到一条 502: Bad Gateway 消息。在终端中输入 npx webpack 时,我还收到以下错误


The 'mode' option has not been set,webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

ERROR in ./src/index.js 1:11-26
Module not found: Error: Can't resolve 'http' in '/sandBox/src'

我认为这是因为 index.js 有这个代码,我认为它是容器所必需的。当我删除代码时,我也会得到 502: Bad Gateway

var http = require("http");

http
  .createServer(function (req,res) {
    res.write("Hello World"); //write a response to the client
    res.end(); //end the response
  })
  .listen(8080); //the server object listens on port 8080

我需要将 function component() 代码移到其他地方吗?我最终想要做的是将我的项目从 GitHub 下载到 CodeSandBox 并让 CodeSandBox 像在 GitHub 页面上一样显示它,除了在实时预览中,所以如果有更简单的方法来做到这一点,你能告诉我吗?

我的 CodeSandBox 在这里https://codesandbox.io/s/npm-sandbox-7v4se

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。