![](/img/trans.png)
[英]JS + Browserify: Function not accessible/defined after Browserify build
[英]JS, Browserify: function not defined
我有文件表示:
-js/
- calc.js
- tool.js
-index.html
calc.js 是一个具有以下结构的节点模块:
module.exports = {
calculate: function() {...},
getPrecision: function() {...}
}
和 tool.js 使用require
并添加了一些功能,如下所示:
const fpcalc = require('./fpcalc');
function changeState() {
//some code using fpcalc
}
我使用 Browserify 生成bundle.js
并将其添加为脚本 src。 我在 HTML 页面上的一个按钮是使用onclick=changeState()
。 点击后我得到
ReferenceError: changeState is not defined
at HTMLAnchorElement.onclick
为什么? 有没有其他方法可以使它工作?
函数“changeState”未在您的 tool.js 中导出。 这意味着它仅在您的 bundle.js 内部可见,而在外部不可见。
看看这个: https : //makerlog.org/posts/creating-js-library-builds-with-browserify-and-other-npm-modules
它向您展示了如何在 javascript 中将您的代码公开给全局命名空间。
这里有一个非常简单的方法可以让它像你想要的那样工作。
const fpcalc = require('./fpcalc');
window.changeState = () => {
//some code using fpcalc
}
我有同样的错误,这是我的工作示例。
mac,浏览器https://github.com/perliedman/reproject
1) must use sudo install globally
sudo npm install -g brwoserify
https://github.com/perliedman/reproject
sudo npm install reproject // install locally is fine
must manually create 'dist' folder for later output file use
2) must use --s expose global variable function 'reproject' and or 'toWgs84' you will use later in browser js.
without --s , will get 'reproject' undefined error . https://makerlog.org/posts/creating-js-library-builds-with-browserify-and-other-npm-modules
browserify --help will list all options. -o means output file directory
browserify node_modules/reproject/index.js --s reproject -o node_modules/reproject/dist/reproject.js
html 脚本标签包括你上面的 dist/reproject.js
现在,您不会收到“reproejct”未定义错误
return reproject(_geometry_, ___from_projection, proj4.WGS84, crss)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.