如何在js中使用require函数 [英] how to use require function in js

查看:1638
本文介绍了如何在js中使用require函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入完成后我得到了正确的信用卡信息我在使用时调用了一个函数来验证带有luhn模块的信用卡(npm install luhn):

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;`




未捕获的ReferenceError :require未定义

Uncaught ReferenceError: require is not defined

对不起如果这是一个简单的问题,但因为我找不到npm打包使用的逻辑简短解决方案。 onsubmit 我这次打电话给 kkTahsil()函数。

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.

所以在js中,必须有简单的方法来使用npm模块。但我还没找到。
我需要帮助。

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

推荐答案

require is在浏览器中不可用。它在Node.js中使用。

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

如果你想在客户端使用 require ,那么使用 Browserify

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


Browserify让你通过捆绑所有依赖项来浏览器中的require('modules')。

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

实际上, require 无法在表单中的浏览器中使用,因为它在Node中实现。 require 的问题在于它是同步的。当你可以阻止I / O时它在事件循环的第一个刻度上在服务器端工作,因为还没有绑定事件监听器,但它在浏览器中不会没有问题,因为它必须阻止用户界面的UI整个模块下载,编译和运行的时间。

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:

  • Exporting Node module from promise result
  • javascript - Why is there a spec for sync and async modules?

这篇关于如何在js中使用require函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆