【问题标题】:Trouble requiring a module in ReactJS在 ReactJS 中需要模块时遇到问题
【发布时间】:2023-03-10 15:18:01
【问题描述】:

我是整个 ReactJS 生态系统的初学者,我正在尝试在 React 中构建一个应用程序。我正在使用 create-react-app 工具来创建我的应用程序。下面是这个问题的相关代码:

App.js:

const findWord = require('../word'); //This is where I require the file

import React from 'react';
import ReactDOM from 'react-dom';

class Form extends React.Component {
  constructor(){
    super();
    this.props = {
    }
  }
  getWord(e){
    e.preventDefault();
    let word = ReactDOM.findDOMNode(this.refs.wordInput).value;
    alert(word);
    findWord();
  }
  render() {
    return (
      <div className="search">
        <form className="pure-form">
          <input ref="wordInput" type="text" placeholder="Search . . ."></input>
          <button onClick={this.getWord.bind(this)} className="pure-button pure-button-primary" type="button">Go</button>
        </form>
      </div>
    );
  }
}

export default Form;

word.js:

var scraperjs = require('scraperjs'); //This is where I require the dependency

/* If I take the function out of the module.exports, then run the file with `node src/word.js`, it will work fine, but when I use it in the context of the application, then things go awry. */

module.exports = function(){
  scraperjs.StaticScraper.create('https://news.ycombinator.com/')
      .scrape(function($) {
          return $(".title a").map(function() {
              return $(this).text();
          }).get();
      })
      .then(function(news) {
          console.log(news);
      })
};

我的麻烦是,当我尝试从组件类中请求模块(scraperjs)并使用它时,它会在某些随机依赖项中产生错误。

Error in ./~/win-spawn/index.js
Module not found: 'child_process' in /Users/marknifakos/Documents/new-react-app/word-map-shs/node_modules/win-spawn

 @ ./~/win-spawn/index.js 1:13-37

当我将此模块与普通 node cli 命令一起使用时,它工作得很好,所以问题可能不在于依赖项本身。而且我 100% 确定路径是正确的,所以也不要提出来。

【问题讨论】:

    标签: javascript node.js reactjs module


    【解决方案1】:

    这是因为 child-process 模块是 Node 中的内置模块,浏览器无法访问。这也是为什么您可以使用 cli 访问它,但不能在浏览器中访问它,因为 webpack 没有捆绑它。你最好的办法是在你的 webpack 配置中包含以下内容:

    node:
    {
        "child_process": "empty"
    }
    

    并希望您的依赖不需要使用此模块中的任何方法。

    【讨论】:

    • 我仍然遇到同样的错误。抱歉,如果我没有提供足够的信息。
    • 您可以将您的作品上传到 github 或其他我可以看到的地方吗?
    猜你喜欢
    • 2015-06-01
    • 2012-01-07
    • 1970-01-01
    • 2013-08-13
    • 2013-06-14
    • 2011-01-17
    • 2011-08-06
    • 2020-06-28
    相关资源
    最近更新 更多