Using RequireJS to load UglifyJS’s parser in the browser

UglifyJS has a great parser (parse-js) which is written as a CommonJS module. This works great in node but not so great in the browser. The suggested route to use it browser side is to just manually wrap it in a AMD define or just pull out the exports yourself. It’s easy enough to do but likely a difficulty to maintain going forward.

RequireJS has support for custom plugins – effectively code that can process the content of a file before it is passed into RequireJS’s AMD module system. Ben Hockey has put together a simple CommonJS module loader plugin (cjs) which automatically wraps the content of a CommonJS module with a AMD define.

This makes a great example of why RequireJS is so powerful. For this example I’ve just git clone‘d the content of the UglifyJS repo into my project and used the following RequireJS configuration to tell it where the CommonJS module is based.

	var require = {
		baseUrl: '/js/requirejs',
		packages: [{
			name: 'uglify-js',
			main: 'uglify-js',
			location: '../UglifyJS'
<script src="/js/requirejs/require.js"></script>

Once that is in place it’s just a matter of asking for the module and prefixing the module id with the cjs plugin.

require(['cjs!uglify-js/lib/parse-js'], function(parser) {
	var ast = parser.parse('function saySomething() { alert("Hello!"); }');
	// ...

These simple steps are enough to give us the following parse tree.