在普通 JavaScript 中使用 NPM 库/包

Using an NPM library/package in normal JavaScript

提问人:helpme 提问时间:1/28/2023 更新时间:1/28/2023 访问量:70

问:

我最近在 NPM 中发现了这个名为 vocabulary-level-grader 的,它对我来说真的很突出,所以我决定在上面做一个网站。 这是该包的 github 链接。 这是我到目前为止的代码:

<head>
  <meta charset="UTF-8">
  <meta name="description" content="A simple and lightweight essay writer.">
  <meta name="keywords" content="Essay, Generater, AI, School, OpenAI, Essay Writer">
  <meta name="author" content="Rehan Raj">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1520413152607686"
    crossorigin="anonymous"></script>
  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <link href="narrow-jumbotron.css" rel="stylesheet">
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
  <title>....</title>
  <style>
    #toggle {
      width: 100px;
      height: 100px;
      background: #ccc;
    }
  </style>
  <script src="//code.jquery.com/jquery-1.12.4.js"></script>
  <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <style type="text/css">
    @font-face {
      font-family: 'rbicon';
      src: url(chrome-extension://dipiagiiohfljcicegpgffpbnjmgjcnf/fonts/rbicon.woff2) format("woff2");
      font-weight: normal;
      font-style: normal;
    }
  </style>
</head>
<div class="title">
  <br>
</div>
</head>

<body data-new-gr-c-s-check-loaded="14.1091.0" data-gr-ext-installed="" data-new-gr-c-s-loaded="14.1091.0"
  style="text-decoration-color: rgb(46, 46, 46); background-color: rgb(250, 250, 250); color: rgb(0, 0, 0);">
  <iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>
  <div class="container">
    <div class="header clearfix">
      <nav>
        <ul class="nav nav-pills float-right">
          <li class="nav-item">
            <a class="nav-link active button button2" href="#">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">

          </li>
          <li class="nav-item">
            <a class="nav-link" href="#form" id="a1" onClick="document.getElementById('form1').scrollIntoView();">Start
              writing</a>
          </li>
        </ul>
      </nav>
      <h3 class="text-muted">- <b>...</b></h3>
    </div>

    <div class="jumbotron" style="background: rgb(41,144,99);
background: linear-gradient(90deg, rgba(41,144,99,1) 16%, rgba(18,208,121,1) 50%, rgba(41,144,99,1) 83%);">
      <h8 class="display-3" style="width: 200x; text-decoration-color: rgb(0, 128, 255); color:aliceblue"><strong>Lorem ipsum....</strong></h8>
      <br>
      <br>
      <h1 class="lead" style="color:aliceblue">lorem ipsum</h1>
    </div>
    <div id="form1" class="form-group">

      <form id="frm1" target="dummyframe">
        <p for="topic" class="text-center" style="font-size: x-large;">Write a short (25 words) essay in the
          language you're learning!</p>
        <p for="topic" class="text-center" style="font-size:medium">English only, please.</p>
        <textarea id="input1" rows="5" cols="60" type="textarea" class="form-control"
          placeholder="E.g: homework, cancer etc." style="resize: none; align-items: center; align-self: center; align-content: center; width:600; position: absolute;
      left: 50%;
      transform: translateX(-50%);"></textarea>


        <br><br><br><br><br><br>
        <p class="text-center" style="font-size:large">
          <b>Words:</b>
          <span id="show">0</span><span id="show">/25</span>
        </p>
        <div id="buttons">
          <input type="submit" id="startbutton" value="Check" class="btn btn-lg btn-success button button2"
            onclick="score_test()" style="position: absolute;
      left: 50%;
      transform: translateX(-120%); border:none">
          <button id="copyButton" class="btn btn-lg btn-success button button2" style="background-color:blue; border:0ch; position: absolute;
        left: 50%;
        transform: translateX(5%); display: inline-block; " onclick="CopyToClipboard('demo')">Copy Score</button>
        </div>
      </form><br><br>
      <div id="demo1">
        <p id="demo"></p>
      </div>
    </div>
    <script>

      document.getElementById("show").style.color = "darkred";

      document
        .querySelector("#input1")
        .addEventListener("input", function countWord() {
          let res = [];
          let str = this.value.replace(/[\t\n\r\.\?\!]/gm, " ").split(" ");
          str.map((s) => {
            let trimStr = s.trim();
            if (trimStr.length > 0) {
              res.push(trimStr);
            }
          });
          document.querySelector("#show").innerText = res.length;
          if (res.length < 10) {
            document.getElementById("show").style.color = "darkred";
          }
          if (res.length < 25 && res.length > 10) {
            document.getElementById("show").style.color = "red";
          }

          else if (res.length >= 25) {
            document.getElementById("show").style.color = "darkgreen";
          }
        });
    </script>
    <script>
      $('#a1,#a2').click(function () {
        $('#frm1').effect('highlight', {}, 1000);
        // $('#demo1').effect('highlight',{},1000);
        $('#buttons').effect('highlight', {}, 1000);
      });

    </script>
    <script>
      function CopyToClipboard(id) {
        var r = document.createRange();
        r.selectNode(document.getElementById(id));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(r);
        document.execCommand('copy');
        window.getSelection().removeAllRanges();
        document.getElementById("copyButton").innerHTML = "Copied!"
        setTimeout(function () {
          document.getElementById("copyButton").innerHTML = "Copy Score"
        }, 1500)
      }


    </script>
    <script>
      function score_test() {
        if (document.getElementById("show").style.color == "darkred" || document.getElementById("show").style.color == "red") {
          console.log("test")
          document.getElementById("startbutton").value = "Error!"
          document.getElementById("startbutton").style.background = "red"
          setTimeout(function () {
            document.getElementById("startbutton").value = "Check"
            document.getElementById("startbutton").style.background = "green"
          }, 1500)
        }
        else {
          const grade = require("vocabulary-level-grader")

          const result = grade("
          It was the hunter's first time outside Montana.
          He woke, stricken still with the hours-old vision of ascending through rose-lit cumulus,
          of houses and barns like specks deep in the snowed-in valleys,
          all the scrolling country below looking December—brown and black hills streaked with snow,
          flashes of iced-over lakes,
          the long braids of a river gleaming at the bottom of a canyon.
          Above the wing the sky had deepened to a blue so pure he knew it would bring tears to his eyes if he looked long enough.
          ");
        }
      } 
    </script>
    <footer class="footer">
      <div class="text-center p-4" style="background-color: rgba(0, 0, 0, 0.05);">
      Test
        <a class="fw-bold" href="#">...</a>
      </div>
    </footer>
</body>

上面代码的主要部分是:

const grade = require("vocabulary-level-grader")

          const result = grade("
          It was the hunter's first time outside Montana.
          He woke, stricken still with the hours-old vision of ascending through rose-lit cumulus,
          of houses and barns like specks deep in the snowed-in valleys,
          all the scrolling country below looking December—brown and black hills streaked with snow,
          flashes of iced-over lakes,
          the long braids of a river gleaming at the bottom of a canyon.
          Above the wing the sky had deepened to a blue so pure he knew it would bring tears to his    eyes if he looked long enough.
          ");

显而易见的问题是,这在普通的JavaScript中不起作用。我已经尝试了许多解决方案,例如 ESM 和 Default 上的 jsDelivr,只是为了遇到这些问题(添加图像以增加清晰度): 第一个错误图像requireUncaught ReferenceError: require is not defined at score_test (index.html:165:25) at HTMLInputElement.onclick (VM202 index.html:91:50)

Uncaught SyntaxError: The requested module '/npm/[email protected]/+esm' does not provide an export named 'default' (at jsdelivr-header.js:7:1) 第二个错误图像

我还使用了 browserify 和 unpkg 等替代方案,但不幸的是无济于事。提前致谢

JavaScript HTML 节点 .js 客户端

评论

0赞 Jared Smith 1/28/2023
使用 rollup 或 webpack。该库是 cjs,它与 esm 不兼容。另请注意,它似乎被放弃了:它有 8 个打开的拉取请求,并且在 3 年内没有提交。
0赞 yqlim 1/28/2023
从我在库源代码中看到的内容来看,它不会将浏览器友好的代码发布到 NPM。所以,是的,使用它的唯一方法是使用像 rollup 或 webpack 这样的转译器将代码转换为浏览器友好的代码。
0赞 helpme 1/28/2023
我尝试汇总并得到此错误:我相信它源于这样一个事实,即该库需要然后未导入的依赖项。有什么修复吗?VM360 bundle.js:56 Uncaught ReferenceError: vocabulary is not defined at VM360 bundle.js:56:4
0赞 1/28/2023
您是否在 NPM 中安装了名为 vocabulary-level-grader 的软件包,您可以在命令行界面中使用以下命令:npm install vocabulary-level-grader

答: 暂无答案