虽然看起来它似乎不是最适合这项工作的工具,但browserify可能是最接近你所需的东西。为了完整起见,以下是我使用的工具版本:
Node v0.10.26
和
browserify 3.38.0
。我没有测试其他版本,因此他们可能会有问题。下面是我克隆
uncss
后所采取的步骤:
npm install
, which downloads and sets up the proper packages
Due to some sort of versioning problem with NPM, I had to manually install the graceful-fs
package (a dependency of one of uncss
's dependencies) from Github (it wasn't available via npm
)
npm install https://github.com/isaacs/node-graceful-fs/tarball/v2.0.3
At this point, I ran browserify. It turns out that browserify has a --bare
flag, which does a couple of things:
Alias for both --no-builtins, --no-commondir, and sets
--insert-global-vars
to just "__filename,__dirname". This is handy if you want to run bundles in
node.
With this flag, browserify doesn't inject its own shims for core modules. The full command I used was:
browserify lib/uncss.js --bare > uncss.js
在完成上述步骤后,文件uncss.js
将包含uncss
及其捆绑的依赖项。不幸的是,由于browserify将所有内容都包装在自己的require
函数中,因此现在捆绑的模块最初并没有导出任何东西。
$ node
> require('./uncss')
{}
>
要解决这个问题,我必须将生成的捆绑包的初始行更改为以下内容:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
转换为:
module.exports = (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require,ex;for(var o=0;o<r.length;o++)ex=s(r[o]);return ex})({1:[function(require,module,exports){
注意:这不仅仅是添加
module.exports
- 中间还需要进行一些修改*。
之后,打包似乎可以正常工作了:
$ node
> require('./uncss')
[Function: init]
>
*: 实质上,browserify 定义了一个名为
function s(o, u)
的内部函数,其作用类似于
require
。周围的代码开始通过循环遍历一系列看起来像是“主模块”的列表(在这个例子中只有一个),使用
require
去调用它们,但不存储结果。然后返回整个匿名函数的输出,即
s
,这个类似于
require
的函数(我不确定为什么)。我所要做的就是添加一个变量来存储结果,然后将其
return
出去。