Browserify 简要介绍
1. 浏览器中无法使用Require()
或import
关键字
如果在浏览器中使用的js
文件中存在require()
或者import
,那么如果运行起来之后,打开Development Tools
,将会看到浏览器跑出的一个异常,Uncaught ReferenceError: require is not defined
.
主要问题是因为require()
和import
是nodejs
引入的方法,所以无法在浏览器中使用。
2. 使用js
打包工具来解决问题
其实这种打包工具很多,类似于webpack
、gulp
、browserify
、ender
或者require-kiss
等等。
1) webpack
webpack
应该是最流行的js
打包工具,webpack
功能很强大,支持很多种插件,而且是基于配置文件实现的,非常方便,不过对于简单的demo项目来说稍显复杂。
2) gulp
gulp
与webpack
类似,支持很多插件,也是非常流行的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/…