Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

javascript - how to use require function in js

I get properly credit card info upon input done I called a function to validate credit card with luhn module ( npm install luhn) as I use :

var luhn = require("luhn");
is_valid = luhn.validate(card); // should respond true.
if (!is_valid) {
            console.log("Not a valid credit card");
}
return;`

Uncaught ReferenceError: require is not defined

I am sorry If this is simple question but since I could not find a logic short solution for npm packed usage. onsubmit I call this time kkTahsil() function.

function kkTahsil() {
datalariAl();

var Iyzipay = require('iyzipay');   
var iyzipay = new window.Iyzipay({
    apiKey: 'sandbox-PZ8jicWrEeE1rt1O75FTOegr5lsW3xxx',
    secretKey: 'sandbox-2Q6aaP1FK3HFrXkTsHfftxfiudFMfxxx',
    uri: 'https://sandbox-api.iyzipay.com'
});

var nameOnCard = document.getElementById('name-on-card').value;
var expireMonth = document.getElementById('card-exp-month').value;
var expireYear = document.getElementById('card-exp-year').value;
var cvc= document.getElementById('card-cvv').value;

again same error.

so in js, there must be easy way to use npm modules. But I could not found yet. Please I need a help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

require is not available in the browser. It is used in Node.js.

If you want to use require on the client side then use Browserify:

Browserify lets you require('modules') in the browser by bundling up all of your dependencies.

In fact, require couldn't be available in the browser in the form as it is implemented in Node. The problem with require is that it is synchronous. It works on the server side on the first tick of the event loop when you can block on I/O because no event listeners are bound yet, but it will not work in the browser without problems because it would have to block the UI for the entire time that the modules are downloaded, compiled and run.

In fact synchronous vs asynchronous module loading has been a matter of controversy. See those answers for more details:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...