2016-11-12 50 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