Golo Roden
Golo Roden

Reputation: 150852

Packaging client-side scripts at runtime with support for Common.js

I am writing a web server in Node.js, and I want it (among other things) to deliver a single JavaScript file to the client which contains my client SDK. The SDK is basically an object which provides lots of functionality the client can use.

I need to build the SDK from various sources:

For being able to test my custom code (#2) easily, and for being able to share this code with the server-side as well, it would be great if I could write it according to CommonJS.

I do not have too much experience with bundling things up for the client-side, but I know UglifyJS and Browserify.

If it was only about concatenating some files (and perhaps minifying them), I knew what to do with UglifyJS. If it was only about delivering some stuff that is compatible to CommonJS, I also knew what to do with Browserify. What I don't get is their combination, and this in addition with demand #3 - the dynamically generated code.

This essentially means that I am not able to use Grunt for this, but that everything needs to be done at runtime (please let's not discuss why I want to do it like this).

So … I'm somewhat lost. Can anybody help clarify things for me? How do I have to put all these pieces together so that I finally end up with a single deliverable that can be sent to the client, and that the client can use?

Basically, what the client should end up with is a number of global objects such as $, angular and my very own custom object, but all this by only loading one single file.

How could I do this?

PS: I do not have the need to put the result to disk on the server, if it's a pure in-memory solution that's perfectly fine for me (and is even preferred, as then I do not need write access to the file system).

Upvotes: 1

Views: 388

Answers (2)

alex
alex

Reputation: 12275

What you're looking for is called "asset pipeline".

You can use mincer (I didn't try it, but it looks very promising) or asset-pipeline (certainly will do the job, but is kinda deprecated).

Upvotes: 0

Johannes Ewald
Johannes Ewald

Reputation: 17815

Imho webpack provides all the features you need. It's a bundler like browserify but I find it more flexible and extensible. webpack is agnostic to different module styles (CommonJS, AMD, ES6 or old-school globals) and is able to apply and chain pre-processors on modules. These are called loaders (according to the CommonJS spec) and can be used to generate code dynamically. Usually they transform LESS to CSS or CSS to JavaScript, but they can be used for any dynamic task.

To provide your global $, angular and your custom object you could use the script-loader, which runs the given module classically in a global context.

Upvotes: 1

Related Questions