evantianx / Bloooooooog

Place to record what I thought and learned
0 stars 0 forks source link

[译]如何编写一个浏览器端和Node端均适用的package? #16

Open evantianx opened 7 years ago

evantianx commented 7 years ago

首先创建一个JS包

我们先写一个迷你的package,叫做base64-encode-string。功能为接收一个字符串作为参数,输出它的64位编码版本

对于浏览器,非常简单;我们只需要利用下内置btoa函数:

module.exports = function(string) {
  return btoa(string);
}

对于Node端,遗憾的是没有bota这个函数。所以我们需要创建一个Buffer来替代,然后调用buffer.toString():

module.exports = function(string) {
  return Buffer.from(string, 'binary').toString('base64');
}

现在我们仅仅需要检测我们的运行环境是浏览器端还是Node端即可,这样我们就能调用正确的代码。

在Browserify和Webpack中均定义了process.browser,返回true值,而在Node端中返回false,因此我们可以这样写:

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