Browserify-如何在浏览器中调用通过浏览器生成的文件中捆绑的函数 [英] Browserify - How to call function bundled in a file generated through browserify in browser
问题描述
我是nodejs和browserify的新手.我从链接开始.
I am new to nodejs and browserify. I started with this link .
我有包含此代码的文件main.js
I have file main.js which contains this code
var unique = require('uniq');
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
this.LogData =function(){
console.log(unique(data));
};
现在我用npm安装uniq模块:
Now I Install the uniq module with npm:
npm install uniq
然后,我使用browserify命令将从main.js开始的所有必需模块捆绑到一个名为bundle.js的文件中:
Then I bundle up all the required modules starting at main.js into a single file called bundle.js with the browserify command:
browserify main.js -o bundle.js
生成的文件如下:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var unique = require('uniq');
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
this.LogData =function(){
console.log(unique(data));
};
},{"uniq":2}],2:[function(require,module,exports){
"use strict"
function unique_pred(list, compare) {
var ptr = 1
, len = list.length
, a=list[0], b=list[0]
for(var i=1; i<len; ++i) {
b = a
a = list[i]
if(compare(a, b)) {
if(i === ptr) {
ptr++
continue
}
list[ptr++] = a
}
}
list.length = ptr
return list
}
function unique_eq(list) {
var ptr = 1
, len = list.length
, a=list[0], b = list[0]
for(var i=1; i<len; ++i, b=a) {
b = a
a = list[i]
if(a !== b) {
if(i === ptr) {
ptr++
continue
}
list[ptr++] = a
}
}
list.length = ptr
return list
}
function unique(list, compare, sorted) {
if(list.length === 0) {
return []
}
if(compare) {
if(!sorted) {
list.sort(compare)
}
return unique_pred(list, compare)
}
if(!sorted) {
list.sort()
}
return unique_eq(list)
}
module.exports = unique
},{}]},{},[1])
在我的index.htm页面中包含bundle.js文件之后,如何调用logData函数?
推荐答案
默认情况下,browserify不允许您从浏览器化的代码之外访问模块-如果您要在浏览器化的模块中调用代码,应该将您的代码与模块一起浏览.有关示例,请参见 http://browserify.org/.
By default, browserify doesn't let you access the modules from outside of the browserified code – if you want to call code in a browserified module, you're supposed to browserify your code together with the module. See http://browserify.org/ for examples of that.
当然,您还可以像这样从外部访问显式的方法:
Of course, you could also explicitly make your method accessible from outside like this:
window.LogData =function(){
console.log(unique(data));
};
然后您可以在页面上的其他任何地方调用LogData()
.
Then you could call LogData()
from anywhere else on the page.
这篇关于Browserify-如何在浏览器中调用通过浏览器生成的文件中捆绑的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!