From Webpack to JSPM (0.17)

JSPM is not as mature as webpack, and its ecosystem is not as rich. But it has some cool features, such as being able to load a module from a remote url, which is not possible with webpack, even webpack 2 — at least yet.

This can be useful when you have scenarios where you need to load an arbitrary module, without bundle it inside your app first, while playing nice with dependencies.

If you come from webpack, it can have some pain points that I hit, so I thought I could share these here.

I found a postcss plugin, postcss-url, that allows to url encode images… in theory.

Since postcss is most often run in a node environment, this won’t work with jspm out of the box.

So we need to do the same, but on the client side. There is an option that allows giving a function that takes arguments like the file path and should return a string that will replace the original path. The bad news is that this function is synchronous, and guess what ? When using XHR, if you use it synchronously, you can’t set the content-type :

After some digging, I found a way to keep the synchronous XHR while being able to base64 encode images, thanks to this great SO answer. There is probably a better way, but manipulating buffers is not my thing :

import Plugins from 'jspm-loader-css/src/plugins.js';import Loader from 'jspm-loader-css/src/loader.js';import autoprefixer from 'autoprefixer';import url from 'postcss-url';import mime from 'mime';import path from 'path';

// Since we are in the browser context, we need to do these to base64 encode images// http://stackoverflow.com/a/7372816/302731function getBinary(file){ var xhr = new XMLHttpRequest(); xhr.open("GET", file, false); xhr.overrideMimeType("text/plain; charset=x-user-defined"); xhr.send(null); return xhr.responseText;}