AMD define factory patcher webpack loader

Today I have released AMD define factory patcher webpack loader as open source and available on NPM. It is a webpack loader aimed at solving a problem that some AMD-based JavaScript libraries have developed which renders them incompatible with webpack.

Why is it useful?

Some JavaScript libraries have come to depend on a non-standard feature in the define function in RequireJS, thus rendering them incompatible with the spec-compliant AMD loader in webpack. According to the AMD specification, the factory argument is not optional. However, in the RequireJS implementation, this is apparently not the case.

For example, in RequireJS the following will load the dependency ./some-file, while spec-compliant AMD loaders will treat the array object as the factory.

1
define(['./some-file']);

In order to get the same behavior in spec-compliant AMD loaders, you must specify an empty factory function.

1
2
define(['./some-file'], function() {
});

How does it work?

This loader will preprocess the JavaScript looking for these non-standard define statements where an array of dependencies is specified without a factory function. When passed through this loader, code like this.

1
define(['./some-file']);

Can be transformed into code like this on-the-fly!

1
2
define(['./some-file'], function() {
});

Obviously, you will want to limit it to only process the problem files to avoid breaking spec-compliant libraries. Your webpack.config.js file might look something like this.

1
2
3
4
5
6
7
8
9
10
11
module.exports = {
entry: './entry',
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /path\/to\/problem\/file\.js$/, loader: 'amd-define-factory-patcher-loader' }
]
}
};

All you need to get started is to install the Node.js module via NPM.

1
npm install amd-define-factory-patcher-loader

Isn’t this an ugly solution?

Yes and no. Obviously libraries that depend on this non-standard behavior should be adjusted to include an empty factory function, so if you see one, let the author know! This is just a quick-and-dirty solution that can be used in the meantime, without the need to maintain your own fork of the package.

Comments