浏览一个库而不是一个文件

Browserify a library rather than a file

我正在尝试在浏览器中使用 npm 库。以npm库uniq为例,此时我们首先需要在本地编写使用uniq的代码:

// main.js
var unique = require('uniq');    
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
console.log(unique(data));

然后,我们需要在控制台中运行browserify

browserify main.js -o bundle.js

现在,我们可以在 html 文件中使用它:

<script src="bundle.js"></script>

我的问题是,是否可以对库进行浏览器化,以便 "script" 标签内的任何代码都可以使用它。 例如,在 html部分,我可能要写

<html>
  <head>
    <script src="the_browserified_library.js"></script>
  </head>
  <body>
    <script>
       <!-- the following code may change -->
       var d = [1, 1, 2, 3];
       console.log(unique(d));
       var a = [2, 2, 4, 5];
       console.log(unique(a));
    </script>
  </body>
</html>

如果可能的话,我们将不必在每次更改代码后都浏览(在控制台中)代码。

有谁知道是否可以通过 browserify 或任何其他工具实现?

编辑1:按照@dNitro的回答,我全局安装了globalify,后来报错:

/tmp/client$ globalify uniq -o uniq.js
/usr/local/lib/node_modules/globalify/node_modules/camelcase/index.js:4
    let isLastCharLower = false;
    ^^^
SyntaxError: Unexpected strict mode reserved word
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/usr/local/lib/node_modules/globalify/globalify.js:7:17)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)

所以你想要 global npm 包的变量?!使用 globalify:

安装:

npm install globalify -g

用法:

globalify uniq -o uniq.js

然后在你的 html:

<script src="uniq.js"></script>    
<script>
  var d = [1, 1, 2, 3];
  console.log(uniq(d));
</script>

注意您应该避免污染全局范围。以这种方式编写代码是有害的。 browserify 不仅让你的代码浏览器准备就绪,它还可以帮助你编写干净(不会污染全局 window 范围)、模块化(CommonJS 或 ES6 方式)和未来证明(编写 ES6 并在捆绑时间转换它)和您的应用程序已准备就绪,只需向 bundle.js 文件发送一个 http 请求。

如果每次更改代码时 运行 browserify 对您造成困扰,您可以考虑使用 watchify;它会根据您在文件中所做的每次更改自动重建捆绑包。