2016-11-12 54 views
0

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

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 

当我与普通节点CLI命令使用这个模块,它工作得很好,所以这个问题可能不与依赖自身所在。我100%肯定这些路径是正确的,所以不要提起这个。

回答

0

发生这种情况是因为child-process模块是Node中的内置模块,不能被浏览器访问。这也是为什么你可以使用cli访问它,但不能在浏览器中访问它,因为webpack不会捆绑它。最好的办法是包括在您的WebPack配置如下:

node: 
{ 
    "child_process": "empty" 
} 

希望与你的依赖并不需要使用任何方法从这个模块。

+0

我仍然收到相同的错误。对不起,如果我没有提供足够的信息。 –

+0

你可以上传你的作品到github或其他我能看到的地方吗? – cynicaldevil