Open evantianx opened 7 years ago
我们先写一个迷你的package,叫做base64-encode-string。功能为接收一个字符串作为参数,输出它的64位编码版本
base64-encode-string
对于浏览器,非常简单;我们只需要利用下内置btoa函数:
module.exports = function(string) { return btoa(string); }
对于Node端,遗憾的是没有bota这个函数。所以我们需要创建一个Buffer来替代,然后调用buffer.toString():
bota
Buffer
buffer.toString()
module.exports = function(string) { return Buffer.from(string, 'binary').toString('base64'); }
现在我们仅仅需要检测我们的运行环境是浏览器端还是Node端即可,这样我们就能调用正确的代码。
在Browserify和Webpack中均定义了process.browser,返回true值,而在Node端中返回false,因此我们可以这样写:
process.browser
if (process.browser) { module.exports = function (string) { return btoa(string); }; } else { module.exports = function (string) { return Buffer.from(string, 'binary').toString('base64'); }; }
然而问题没有这么简单...
原文链接: How to write a JavaScript package for both Node and the browser
首先创建一个JS包
我们先写一个迷你的package,叫做
base64-encode-string
。功能为接收一个字符串作为参数,输出它的64位编码版本对于浏览器,非常简单;我们只需要利用下内置btoa函数:
对于Node端,遗憾的是没有
bota
这个函数。所以我们需要创建一个Buffer
来替代,然后调用buffer.toString()
:现在我们仅仅需要检测我们的运行环境是浏览器端还是Node端即可,这样我们就能调用正确的代码。
在Browserify和Webpack中均定义了
process.browser
,返回true值,而在Node端中返回false,因此我们可以这样写:然而问题没有这么简单...