01. browserify

627 阅读2分钟

Browserify 简要介绍

1. 浏览器中无法使用Require()import关键字

如果在浏览器中使用的js文件中存在require()或者import,那么如果运行起来之后,打开Development Tools,将会看到浏览器跑出的一个异常,Uncaught ReferenceError: require is not defined.

主要问题是因为require()importnodejs引入的方法,所以无法在浏览器中使用。

浏览器调用require异常

2. 使用js打包工具来解决问题

其实这种打包工具很多,类似于webpackgulpbrowserifyender或者require-kiss等等。

1) webpack

webpack应该是最流行的js打包工具,webpack功能很强大,支持很多种插件,而且是基于配置文件实现的,非常方便,不过对于简单的demo项目来说稍显复杂。

2) gulp

gulpwebpack类似,支持很多插件,也是非常流行的js打包工具,但是与webpack不同,需要编写打包用的js文件。

3) browserify

browserify使用更简单的命令行语句来进行打包,非常适用于小规模的web项目,但是对于插件支持不足。

4) ender|requrire-kiss及其他

还有很多类似的的打包工具,就不一一描述了。

3. browserify简单实用介绍

上面介绍了很多种打包工具,这里主要介绍browserify

1) 安装browserify

npm install browserify -g

2) 打包js文件

# cannot debug in the origin js file
browserify index.js -o bundle.js            
# enable debug in the origin js file
browserify index.js -o bundle.js -d true    
  • browserify: 命令行工具名称
  • index.js: 要打包的入口文件
  • -o bundle.js: 将打包后的结果输出到bundle.js
  • -d true: 设置debug模式为true,这样能够在IDE中按照原有文件进行调试。
// index.js
// ...
var inheritDemo = require("./inherit");
inheritDemo.inheritDemo();

var closuresDemo = require("./closures");
console.log(closuresDemo.closureThisTest1()());
console.log(closuresDemo.closureThisTest2()());
console.log(closuresDemo.closureVariableTest1());
console.log(closuresDemo.closureVariableTest2());
// ...
// bundle.js
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
    // the origin implementation of all your js files
    // ...
}

可以看到经过browserify之后,在bundle.js文件中将require()方法实现了一遍,这就是能够在浏览器中工作的原理。

NOTE: 需要注意一点,在VSCode中,browserify命令执行的文件夹应该与bundle.js是同一个文件夹,否则,VSCode中调试总是无法命中断点。

4. browserify的其他功能

之前提到过,browserify使用命令行的方式提供服务,所以涉及到很多命令函的参数,可以refer下面的link查看其他的命令行参数: github.com/browserify/…