简体   繁体   English

导入 npm 模块后 React 网页无法编译

[英]React web page can't compile after importing npm modules

I have a webpage that has a button, built with react.我有一个带有按钮的网页,使用 react 构建。 I want to execute some js code when the button is clicked.我想在单击按钮时执行一些 js 代码。 The code I want to execute is an npm module I made that requires 'pg' and 'fs', and will handle communications with a psql server.我要执行的代码是我制作的一个 npm 模块,它需要“pg”和“fs”,并将处理与 psql 服务器的通信。 When I add "const database = require('../datadb/datadb.js')" (line 2) to my code, react fails to compile.当我将“const database = require('../datadb/datadb.js')”(第 2 行)添加到我的代码中时,react 无法编译。 Below is the code for my button.下面是我的按钮的代码。

import React, { Component } from "react";
const database = require('../datadb/datadb.js'); //HERE is the line that causes compilation failure

/* 
A function that handles when the LoadData button is clicked. This will allow for the data to be loaded in and stored into a database that can then be referenced.
*/
function Data() {
  alert("'The data is loading'"); //Creates a pop up box
  //HERE is where I will want to execute my modules code
}

/*
This function creates a component for the buttons. 
*/
class LoadData extends Component {
  render() {
    return (
      <div className="App">
        <button onClick={Data}>Load Data</button>
        <button>Open</button>
        <button>Save</button>
      </div>
    );
  }
}
export default LoadData;

Which gives the error message:这给出了错误消息:

Failed to compile.

./src/datadb/node_modules/semver/semver.browser.js
  Line 1180:37:  'define' is not defined  no-undef
  Line 1181:3:   'define' is not defined  no-undef
  Line 1185:35:  'define' is not defined  no-undef
  Line 1186:3:   'semver' is not defined  no-undef

I have tested my datadb module by itself self and it has worked properly.我已经自己测试了我的datadb模块并且它运行正常。 The webpage loads properly and the button works (as in the alert works properly on line 10)网页正常加载,按钮正常工作(如第 10 行的警报正常工作)

I am very new to web page related coding like react and javascript (most of my experience is in Java and some C) and was handed this project to implement my code, but I did not make the webpage or the button, so I am very unfamiliar with react.我对像 react 和 javascript 这样的网页相关编码很陌生(我的大部分经验是在 Java 和一些 C 方面),并被交给这个项目来实现我的代码,但我没有制作网页或按钮,所以我很不熟悉反应。 Are npm modules not exportable to react? npm 模块是否不可导出以进行反应?

Here is the datadb.js file as requested这是请求的 datadb.js 文件

var fs = require('fs')
const {Client} = require('pg')






/**Connects to the client, then inserts all of the data from the given data array
 * 
 * @param {*} dataArray the data to insert
 * @param {*} client the DB client to connect to
 */
var insertRawData = async function(dataArray) {

    const client = new Client({
        user: "postgres",
        password: "password123",
        post: "5432",
        database: "first"
    })
    try {
        await client.connect()
        await client.query("BEGIN")

        var length = dataArray.length;
        for(let i = 0; i < length; i++) {
            queryString = "INSERT INTO rawdata.rawtable VALUES ( " + dataArray[i][0] + ", '" + dataArray[i][1] + "', " + dataArray[i][2] + ", " + dataArray[i][3] + ", " + dataArray[i][4] + ", " + dataArray[i][5] + ", " + dataArray[i][6] + ", " + dataArray[i][7] + ", " + dataArray[i][8] + ", " + dataArray[i][9] + ", " + dataArray[i][10] + ")" ;
            await client.query(queryString)
            console.log("NEW ROW INSERTED: " + queryString);
        }
        await client.query("COMMIT")

    } catch (err) {
        console.log("somethings wrong" + err)
    } finally {
        await client.end()
        console.log("Connection ended")
    }
}


/** 
 * Deletes all of the entries in the rawdata.rawtable table
 */
var deleteAllData = async function() {

    const client = new Client({
        user: "postgres",
        password: "password123",
        post: "5432",
        database: "first"
    })

    try {
        await client.connect()
        await client.query("DELETE FROM rawdata.rawtable WHERE year=1 OR year!=1")
    } catch (err) {
        console.log("somethings wrong" + err)
    } finally {
        await client.end()
        console.log("Connection ended")
    }
}


/** 
 * Returns the entire database
 */
var getAllData = async function () {
    const client = new Client({
        user: "postgres",
        password: "password123",
        post: "5432",
        database: "first"
    })

    var data;
    try {
        await client.connect()
        data = await client.query("SELECT * FROM rawdata.rawtable")
    } catch (err) {
        console.log("somethings wrong" + err)
    } finally {
        await client.end()
        console.log("Connection ended")
    }
    return data;
}

/** takes raw data returned from a SELECT psql query as input, returns the data 
 * in a 2d array format
 * 
 * @param {*} data the raw data returned from a query
 * @returns {*} the parsed data
 */
var parseDataFromQuery = async function(data){
    var returnValue = [];
    console.log("DATA: " + data.rows[0].year);

    var dataSize = data.rows.length;

    for(var i = 0; i < dataSize; i++){
        returnValue.push([data.rows[i].year, data.rows[i].month, data.rows[i].occupancy, data.rows[i].adr, data.rows[i].revpar, data.rows[i].supply, data.rows[i].demand, data.rows[i].revinue, data.rows[i].cprops, data.rows[i].crooms, data.rows[i].sparts]);
    }
    console.log(returnValue);
}



var selectTest = async function(){
    const client = new Client({
        user: "postgres",
        password: "password123",
        post: "5432",
        database: "first"
    })

    var data;
    try {
        await client.connect()
        data = await client.query("SELECT * FROM rawdata.rawtable WHERE year=9 AND month='Jan'")
    } catch (err) {
        console.log("somethings wrong" + err)
    } finally {
        await client.end()
        console.log("Connection ended")
    }

    console.log(parseDataFromQuery(data, ['year']));
    //return data;
}



/**
 * Exports the functions to be used elsewhere
 */
module.exports = {
    insertRawData: insertRawData,
    deleteAllData: deleteAllData,
    getAllData: getAllData,
    selectTest: selectTest,
    parseDataFromQuery: parseDataFromQuery
};

So as we figure it out, you tried to run a server side code (using PostgreSQL lib) in the react frontend app, that what causes your code to doesn't compile.因此,正如我们发现的那样,您尝试在 React 前端应用程序中运行服务器端代码(使用 PostgreSQL 库),这导致您的代码无法编译。

So I will suggest you to take a look at those links to understand how to create a NodeJS API server, with Express and PostgreSQL.因此,我建议您查看这些链接以了解如何使用 Express 和 PostgreSQL 创建 NodeJS API 服务器。

  1. https://medium.com/@olinations/build-a-crud-template-using-react-bootstrap-express-postgres-9f84cc444438 (ReactJS + Express + PostgreSQL) https://medium.com/@olinations/build-a-crud-template-using-react-bootstrap-express-postgres-9f84cc444438 (ReactJS + Express + PostgreSQL)
  2. https://blog.logrocket.com/setting-up-a-restful-api-with-node-js-and-postgresql-d96d6fc892d8/ (Only Express + PostgreSQL) https://blog.logrocket.com/setting-up-a-restful-api-with-node-js-and-postgresql-d96d6fc892d8/ (仅限 Express + PostgreSQL)
  3. https://kb.objectrocket.com/postgresql/nodejs-express-postgresql-tutorial-part-1-960 (Only Express + PostgreSQL) https://kb.objectrocket.com/postgresql/nodejs-express-postgresql-tutorial-part-1-960 (仅 Express + PostgreSQL)

And finally recommend you to take a look at Axios , which will help you to make call to your API.最后推荐你看看Axios ,它会帮助你调用你的 API。

Have fun !玩得开心 !

A few possible solutions for this issue.此问题的几种可能解决方案。

  1. Please use import instead of require for your module - although it seems the same, Webpack might treat dynamic import and requirements in a different way while compiling the code.请为您的模块使用import而不是require - 尽管看起来相同,但 Webpack 在编译代码时可能会以不同的方式处理动态导入和需求。
  2. Judging by the name of your file, it's something that should rather be executed on the server-side (aka Node.js service), not the client-side (in this case - React Single Page Application).从您的文件名称来看,它应该在服务器端(又名 Node.js 服务)而不是客户端(在这种情况下 - React Single Page Application)上执行。 Perhaps try moving the logic associated with the database on the server side and compile this logic there?也许尝试在服务器端移动与数据库关联的逻辑并在那里编译这个逻辑?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM