将 browserify 与 node 模块一起使用时出现问题

问题描述

我想将 pbkdf2 npm 库包含到我的 JS/html 页面中,这些页面只是纯 Javascript,节点不可用。

browserify 应该有我在那里。我编写了一个使用该功能的简短 JS 文件 (main.js)。

var callback = function (err,key) {
    console.log(key);
}


function hashIt(hac,callback)  {
    pbkdf2.pbkdf2(hac,hac,10000,32,'sha256',callback);
    
}

我使用 browserify 使其成为“可包含的”JS 文件

browserify main.js -o bundle.js

bundle.js 文件看起来不错,就像 browserify 发挥了它的魔力一样。

我在 HTML 页面中包含了 bundle.js 文件,但是我无法访问 hashIt 函数。是否有一种特殊的方式来包含或调用 bundle.js 中的函数

解决方法

window 对象上导出您的函数。

var callback = function (err,key) {
    console.log(key);
}


function hashIt(hac,callback)  {
    pbkdf2.pbkdf2(hac,hac,10000,32,'sha256',callback);   
}

window.hashIt = hashIt;

在浏览器中。

hashIt('test',(err,key) => console.log(key.toString()))
> ��&�`=�&
0q$.��bp�u��<!x���GV�;

Chrome 截图。

enter image description here