Я получаю ошибку React Webpack, когда пытаюсь импортировать функциюJavascript

Форум по Javascript
Ответить
Anonymous
 Я получаю ошибку React Webpack, когда пытаюсь импортировать функцию

Сообщение Anonymous »

Я работаю на веб -сайте, используя Mern Stack, и мне нужно реализовать функцию для запуска при нажатии кнопки. Я уже выполнял функцию, но всякий раз, когда я пытаюсь импортировать и использовать ее на странице React, я просто получаю ошибку, и я искренне не знаю, почему. Функция работает, когда я запускаю его в собственном файле.

Код: Выделить всё

import xlsxpopulate from 'xlsx-populate';

function calculateInterest(price, interestRate) {
return (price * interestRate) / 3000;
}

console.log(calculateInterest(809055, 0.5));

function addMonth(dateStr, count) {
let [day, month, year] = dateStr.split('/').map(Number);

let date = new Date(year, month - 1, day);

date.setMonth(date.getMonth() + count);

let newDay = date.getDate().toString().padStart(2, '0');
let newMonth = (date.getMonth() + 1).toString().padStart(2, '0');
let newYear = date.getFullYear();

return `${newDay}/${newMonth}/${newYear}`;
}

let a = 0;

function dateDifference(dateStr1, dateStr2) {
let [day1, month1, year1] = dateStr1.split('/').map(Number);
let [day2, month2, year2] = dateStr2.split('/').map(Number);

let date1 = new Date(year1, month1 - 1, day1);
let date2 = new Date(year2, month2 - 1, day2);

let diffTime = Math.abs(date2 - date1);

return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
}

let originalPrice = 0;

export function populateExcelForMonthly(
paymentDate,
price,
monthlyPayment,
interestRate
) {
const monthCount = Math.floor(price / monthlyPayment);

originalPrice = price;
let paymentLeft = price;
let _paymentLeft = price;
let _paymentDate = paymentDate;
let currentInterest = 0;
let totalInterest = 0;
const currentDate = new Date();
let day = currentDate.getDate();
let month = currentDate.getMonth() + 1;
let year = currentDate.getFullYear();
let formattedCurrentDate = `${day.toString().padStart(2, '0')}/${month
.toString()
.padStart(2, '0')}/${year}`;
let previousDate = formattedCurrentDate;

let i;

xlsxpopulate.fromFileAsync('./src/util/template.xlsx').then((workbook) => {
for (i = 0; i < monthCount;  i++) {
// Aylık Ödeme Tarihi
workbook
.sheet('Sheet1')
.cell(`B${5 + i}`)
.value(_paymentDate);

// Aylık Ödenicek Miktar (Ana para bitene kadar sabit)
workbook
.sheet('Sheet1')
.cell(`C${5 + i}`)
.value(monthlyPayment);

currentInterest =
calculateInterest(_paymentLeft, interestRate) *
dateDifference(previousDate, _paymentDate);

_paymentLeft -= monthlyPayment;
_paymentLeft = _paymentLeft + currentInterest;
// Ödenmesi Gereken Paranın Geri Kalanı
workbook
.sheet('Sheet1')
.cell(`D${5 + i}`)
.value(_paymentLeft);

// Vade Farkı
workbook
.sheet('Sheet1')
.cell(`E${5 + i}`)
.value(currentInterest);

paymentLeft -= monthlyPayment;
paymentLeft += currentInterest;

currentInterest = 0;

// Önceki tarihten ödeme tarihine kadar olan mesafe
workbook
.sheet('Sheet1')
.cell(`F${5 + i}`)
.value(dateDifference(previousDate, _paymentDate));

previousDate = _paymentDate;
_paymentDate = addMonth(_paymentDate, 1);
}

workbook
.sheet('Sheet1')
.cell(`B${5 + i}`)
.value(_paymentDate);

workbook
.sheet('Sheet1')
.cell(`C${5 + i}`)
.value(paymentLeft);

workbook
.sheet('Sheet1')
.cell(`D${5 + i}`)
.value('0,00');

currentInterest =
calculateInterest(_paymentLeft, interestRate) *
dateDifference(previousDate, _paymentDate);
workbook
.sheet('Sheet1')
.cell(`E${5 + i}`)
.value(currentInterest);

totalInterest += currentInterest;
workbook
.sheet('Sheet1')
.cell(`F${5 + i}`)
.value(dateDifference(previousDate, _paymentDate));

workbook
.sheet('Sheet1')
.cell(`B${6 + i}`)
.value('Toplam Ödeme');

workbook
.sheet('Sheet1')
.cell(`B${7 + i}`)
.value('Toplam Vade Farkı');

workbook
.sheet('Sheet1')
.cell(`C${6 + i}`)
.value(originalPrice + paymentLeft);

originalPrice = 0;
totalInterest = 0;

workbook
.sheet('Sheet1')
.cell(`C${7 + i}`)
.value(paymentLeft);

return workbook.toFileAsync('./src/util/outputs/output.xlsx');
});
}
< /code>
страница React Я пытаюсь импортировать функцию в: < /p>
import React, { useState } from 'react';

//import PaymentForm from '../components/PaymentForm';
import { PaymentSetup } from '../components/PaymentSetup';
import { PaymentStructure } from '../components/PaymentStructure';
import { populateExcelForMonthly } from '../hooks/populate';
import { useMultistepForm } from '../hooks/useMultistepForm';

const Create = () => {
const INITIAL_DATA = {
title: '',
startDate: '',
currency: '',
price: 0,
interestRate: 0,
paymentType: '',
monthlyPayment: 0,
};

const [data, setData] = useState(INITIAL_DATA);

function updateFields(fields) {
setData((prev) =>  {
return { ...prev, ...fields };
});
}

const {
steps,
currentStepIndex,
step,
isFirstStep,
previous,
next,
isLastStep,
} = useMultistepForm([
,
,
]);

async function onSubmit(e) {
e.preventDefault();

if (isLastStep) {
const payment = {
title: data.title,
monthlyPayment: data.monthlyPayment,
startDate: data.startDate,
currency: data.currency,
price: data.price,
interestRate: data.interestRate,
paymentType: data.payment,
};
const response = await fetch('/api/payments', {
method: 'POST',
body: JSON.stringify(payment),
headers: {
'Content-Type': 'application/json',
},
});
const json = await response.json();

if (response.ok) {
INITIAL_DATA.title = '';
INITIAL_DATA.startDate = '';
INITIAL_DATA.currency = '';
INITIAL_DATA.price = 0;
INITIAL_DATA.interestRate = 0;
INITIAL_DATA.paymentType = '';
INITIAL_DATA.monthlyPayment = 0;
console.log('Yeni sözleşme eklendi:', json);
}
} else {
next();
}
}

// Multi-step Form
return (



{currentStepIndex + 1} / {steps.length}

{step}

{!isFirstStep && (

Geri

)}
{isLastStep ? (

Bitir

) : (
İleri
)}



);
};

export default Create;

< /code>
ошибка: < /p>
Failed to compile.

Module not found: Error: Can't resolve 'buffer' in '/home/canakil/Code/cemil-mern/frontend/node_modules/safe-buffer'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
WARNING in ./node_modules/sax/lib/sax.js 139:13-37
Module not found: Error: Can't resolve 'stream' in '/home/canakil/Code/cemil-mern/frontend/node_modules/sax/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case.  Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }

WARNING in [eslint]
src/pages/Create.js
Line 6:10:  'populateExcelForMonthly' is defined but never used  no-unused-vars

ERROR in ./node_modules/safe-buffer/index.js 3:13-30
Module not found: Error: Can't resolve 'buffer' in '/home/canakil/Code/cemil-mern/frontend/node_modules/safe-buffer'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }

ERROR in ./node_modules/xlsx-populate/lib/Encryptor.js 12:15-32
Module not found: Error: Can't resolve 'crypto' in '/home/canakil/Code/cemil-mern/frontend/node_modules/xlsx-populate/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
- install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "crypto": false }

ERROR in ./node_modules/xlsx-populate/lib/Workbook.js 4:11-24
Module not found: Error: Can't resolve 'fs' in '/home/canakil/Code/cemil-mern/frontend/node_modules/xlsx-populate/lib'

webpack compiled with 3 errors and 2 warnings
Я был бы признателен за какое -либо направление, почему я получаю эту ошибку и что это значит.


Подробнее здесь: https://stackoverflow.com/questions/794 ... a-function
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»