我对NodeJS和Browserify很陌生。
有文件main.js,其中包含以下代码
var unique = require('uniq');
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
this.LogData =function(){
console.log(unique(data));
};
现在用NPM安装Uniq模块:
npm install uniq
然后,将所有必需的模块(从main.js开始)捆绑到一个名为bundle.js的文件中,并使用Browserify命令:
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])
将bundle.js文件包含到index.htm页面后,如何调用logData函数?
发布于 2018-05-03 16:34:17
默认情况下,Browserify不允许从浏览器序列化代码之外访问模块。如果要调用浏览器序列化模块中的代码,则应该将代码与模块一起浏览。见Browserify.org/这方面的例子。
当然,也可以显式地让方法从外部访问,如下所示:
window.LogData =function(){
console.log(unique(data));
};
发布于 2018-05-03 17:42:35
使用Browserify捆绑独立模块的关键部分是--s
选项。它使用节点module.exports
作为全局变量从模块中导出的任何内容公开。该文件可以包含在<script>
标签中。
如果由于某种原因需要暴露全局变量,才需要执行此操作。
下面是一个例子:
browserify index.js --s module > dist/module.js
这会将我们的模块公开为全局变量。
发布于 2018-05-14 12:32:56
--standalone 了解一下。
在你的mian.js里面加一句导出模块的:
module.exports = main;
生成的时候加这个参数:browserify xxx.js --standalone Main> xxxx.bundle.js
然后就可以直接在外部直接
var ex = new Main();
ex.LogData();
https://stackoverflow.com/questions/-100004018
复制相似问题